0
我寫的回調處理程序與谷歌帳戶登錄:去 - 的oauth2無法獲取令牌:壞請求
func GoogleCallbackHandler(w http.ResponseWriter, r *http.Request) {
conf:=&oauth2.Config{
ClientID:"700740834863-m4om9r91htn19htq2b6a05fu6vu4j7i5.apps.googleusercontent.com",
ClientSecret:"...-rB",
RedirectURL:"http://localhost:3000/auth/google/callback",
Scopes:[]string{"profile"},
Endpoint:google.Endpoint,
}
fmt.Println(conf.AuthCodeURL("state"))
code := r.URL.Query().Get("code")
token, err := conf.Exchange(oauth2.NoContext, code)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
client := conf.Client(oauth2.NoContext, token)
resp, err := client.Get("https://www.googleapis.com/userinfo/v2/me")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
raw, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var profile map[string]interface{}
if err := json.Unmarshal(raw, &profile); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
session, _ := util.GlobalSessions.SessionStart(w, r)
defer session.SessionRelease(w)
session.Set("id_token", token.Extra("id_token"))
session.Set("access_token", token.AccessToken)
session.Set("profile", profile)
// // Redirect to logged in page
http.Redirect(w, r, "/user", http.StatusMovedPermanently)
}
在main
,我所服務的處理
http.HandleFunc("/",route.IndexHandler)
http.HandleFunc("/auth/google/",route.GoogleCallbackHandler)
http.Handle("/user",negroni.New(
negroni.HandlerFunc(route.IsAuthenticated),
negroni.Wrap(http.HandlerFunc(route.UserHandler)),
))
我遇到我得到了同樣的問題我的老問題: oauth2 cannot fetch token: bad request
oauth2: cannot fetch token: 400 Bad Request
Response: {
"error" : "invalid_request",
"error_description" : "Missing required parameter: code"
}
在我上次問這個問題後,我設法用上面的代碼修復了它,成功地訪問並獲取了數據,但是昨晚它突然再次出現這個錯誤,我不明白爲什麼在最近幾天工作後它不再工作使用完全相同的代碼
如何從AuthCodeURL
獲得code
?有沒有辦法讓代碼交換而不重定向到任何其他處理程序?我想要處理,在短短一個此處理所有的事情
打印出來(日誌)的請求期間'code'價值解決它。它是空的嗎? – elithrar
就是這樣。我不知道爲什麼幾天前,當我登錄時,它記錄了代碼,令牌,甚至是個人資料 – necroface