【问题标题】:oauth2 cannot fetch token: bad requestoauth2 无法获取令牌:错误请求
【发布时间】:2016-06-22 00:15:44
【问题描述】:

我编写了一个处理程序,以便在访问路由 /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 帐户获取令牌和信息

【问题讨论】:

  • 您是否定义了code url 参数?我找不到它。
  • @SimoEndre 我该如何定义它?

标签: go oauth-2.0 request google-oauth token


【解决方案1】:

您正在尝试访问未在您的 url 中定义的 url 参数 (code)。

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

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

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

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

【讨论】:

  • 我一直在学习如何使用 Google OAuth2。我没有得到它:我怎样才能包含或明确声明它?
  • 该错误与 Google OAuth2 无关。这与您尝试解析 url 参数的方式有关。该错误表明您正在尝试从 url 访问 code 参数,但这个参数不存在。检查这个:golang.org/pkg/net/url/#URL.Querygolang.org/pkg/net/url/#Values.Get
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-14
  • 2019-09-06
  • 2014-09-01
  • 1970-01-01
  • 2016-12-03
  • 2012-06-08
  • 1970-01-01
相关资源
最近更新 更多