我编写了一个处理程序,以便在访问路由 /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/