oauth2 无法获取令牌:错误请求

oauth2 cannot fetch token: bad request

我编写了一个处理程序,以便在访问路由 /auth/google/callback 时,我尝试通过 OAuth2 使用 Google 帐户登录。处理程序是这样实现的:

package route

import (
    "net/http"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "fmt"
)

func GoogleOAuthHandler(w http.ResponseWriter, r *http.Request) {
    conf:=&oauth2.Config{
        ClientID:"myclientid",
        ClientSecret:"myclientsecret",
        RedirectURL:"http://localhost:3000",
        Scopes:[]string{
            "https://www.googleapis.com/auth/userinfo.profile",
            "https://www.googleapis.com/auth/userinfo.email",
        },
        Endpoint:google.Endpoint,
    }

    code := r.URL.Query().Get("code")

    token, err := conf.Exchange(oauth2.NoContext, code)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    fmt.Println(token)

    http.Redirect(w, r, "/", http.StatusMovedPermanently)
}

func main()中设置http.HandleFunc("/auth/google/callback",route.GoogleOAuthHandler)

当我访问该路径时,它会在浏览器上抛出这样的错误:

oauth2: cannot fetch token: 400 Bad Request
Response: {
  "error" : "invalid_request",
  "error_description" : "Missing required parameter: code"
}

我错过了什么吗?请指导我正确访问 OAuth2 并从 Google 帐户

获取令牌和信息

您正在尝试访问未在您的 url.

中定义的 url 参数 (code)

r.URL.Query().Get() returns 在 url 地址中定义的 url 参数。在您的情况下,您正在搜索缺少的 code 参数。

检查Exchange方法,这会将授权码转换为令牌。

func (c *Config) Exchange(ctx context.Context, code string) (*Token, error).

您案例中的令牌是一个 url 参数,但未声明。总而言之,请在 url 中包含令牌字符串作为参数,否则请在代码中的某处声明。