go - oauth2 无法获取 token : bad request

标签 go oauth-2.0 request google-oauth token

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

最佳答案

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

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

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

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

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

关于go - oauth2 无法获取 token : bad request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35860811/

相关文章:

javascript - 无需身份验证即可使用 Youtube API

android - 如何将客户端 ID 添加到 Google Drive Client API for Java

scala - 使用 akka http,如何将请求 header 注入(inject)到服务器中的传入路由中?

python-3.x - SyntaxError : invalid syntax : except urllib2. HTTPError,e:

http - 有没有一种方法可以检查HTTP请求中的无效查询参数?

node.js - Websocket 连接断开使用 Golang 的 gorilla/websocket 包

go - code.google.com/p/go.crypto/pbkdf2 文件未找到?

go - 使用互斥锁 - 仍然是死锁

Gob 解码给出 "DecodeValue of unassignable value"错误

google-apps-script - 如何使用 oauth 2.0 从 appscript 到 Google API 进行授权?