我编写了一个处理程序,以便在访问路径/auth/google/callback
时尝试使用Google帐户通过OAuth2登录。该处理实现这样的:oauth2无法获取令牌:不好的请求
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我如何定义它? – necroface