2016-03-08 150 views
0

我编写了一个处理程序,以便在访问路径/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帐户获取令牌和信息

+1

您是否定义了'code' url参数?我找不到它。 –

+0

@SimoEndre我如何定义它? – necroface

回答

1

您正在尝试访问URL中未定义的url参数(code)。

r.URL.Query().Get()返回url地址中定义的url参数。在你的情况下,你正在寻找code参数,这是缺少。

检查Exchange方法,这会将授权码转换为令牌。

func (c *Config) Exchange(ctx context.Context, code string) (*Token, error). 

你的情况的令牌是一个url参数,但它没有声明。总结起来,请将url中的标记字符串作为参数包含在其他代码中。

+0

我一直在学习如何使用Google OAuth2。我没有得到它:我怎样才能包含或专门声明? – necroface

+1

该错误与Google OAuth2无关。这与你如何解析url参数有关。该错误表示您正在尝试访问url的'code'参数,但是这个参数不存在。检查这些:https://golang.org/pkg/net/url/#URL.Query,https://golang.org/pkg/net/url/#Values.Get –