无法使用软件包“golang.org/x/oauth2”与facebook进行身份验证:“缺少redirect_uri参数”

时间:2016-04-17 02:38:54

标签: facebook go oauth-2.0 google-oauth

此代码有效:

func handleFacebookCallback(w http.ResponseWriter, r *http.Request) {
    state := r.FormValue("state")
    if state != oauthStateString {
        fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    code := r.FormValue("code")

////////////////////////////////////////////////////    
    Url, err := url.Parse(oauthConf.Endpoint.TokenURL)
    if err != nil {
        log.Fatal("Parse: ", err)
    }
    parameters := url.Values{}
    parameters.Add("client_id", oauthConf.ClientID)
    parameters.Add("client_secret", oauthConf.ClientSecret)
    parameters.Add("redirect_uri", "http://localhost:9090/oauth2callback")
    parameters.Add("code", code)
    Url.RawQuery = parameters.Encode()
    resp, err := http.Get(Url.String())

    if err != nil {
        fmt.Printf("Get: %s\n", err)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }
    defer resp.Body.Close()

但是当我将标记//////...下方的部分替换为:

    token, err := oauthConf.Exchange(oauth2.NoContext, code)
    if err != nil {
        fmt.Printf("oauthConf.Exchange() failed with '%s'\n", err)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

我明白了:

  

oauthConf.Exchange()因'oauth2失败:无法获取令牌:400错误   请求响应:{“error”:{“message”:“缺少redirect_uri   参数 “” 类型 “:” OAuthException”, “代码” 191 “fbtrace_id”: “XXXX”}}“

golang.org/x/oauth2无法与code交换token吗?

1 个答案:

答案 0 :(得分:1)

我发现了什么遗失。我显然需要在RedirectURL结构中添加oauthConfig字段以使Exchange()正常工作。对于Slack或GitHub来说情况并非如此,但显然FB稍微挑剔。

var oauthConf = &oauth2.Config{
        ClientID:     "YOUR_CLIENT_ID",
        ClientSecret: "YOUR_CLIENT_SECRET",
        RedirectURL:  "http://localhost:9090/oauth2callback", /* Fixed! */
        Scopes:       []string{"public_profile"},
        Endpoint:     facebook.Endpoint,
    }