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