我編寫了一個(gè)處理程序,以便在訪問路由/auth/google/callback時(shí)嘗試通過 OAuth2 使用 Google 帳戶登錄。處理程序是這樣實(shí)現(xiàn)的:package routeimport ( "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)是設(shè)置當(dāng)我訪問該路徑時(shí),它會(huì)在瀏覽器上引發(fā)這樣的錯(cuò)誤:oauth2: cannot fetch token: 400 Bad RequestResponse: { "error" : "invalid_request", "error_description" : "Missing required parameter: code"}我錯(cuò)過了什么?請(qǐng)指導(dǎo)我正確訪問 OAuth2 并從 Google 帳戶獲取令牌和信息
1 回答

拉丁的傳說
TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
您正在嘗試訪問code
未在您的 url 中定義的 url 參數(shù) ( )。
r.URL.Query().Get()
返回 url 地址中定義的 url 參數(shù)。在您的情況下,您正在搜索code
缺少的參數(shù)。
檢查Exchange
方法,這會(huì)將授權(quán)代碼轉(zhuǎn)換為令牌。
func (c *Config) Exchange(ctx context.Context, code string) (*Token, error).
您的情況下的令牌是一個(gè) url 參數(shù),但未聲明??偠灾?,請(qǐng)?jiān)?url 中包含令牌字符串作為參數(shù),否則請(qǐng)?jiān)诖a中的某處聲明。
- 1 回答
- 0 關(guān)注
- 404 瀏覽
添加回答
舉報(bào)
0/150
提交
取消