【问题标题】:Unable to use package "golang.org/x/oauth2" to authenticate with facebook: "Missing redirect_uri parameter"无法使用包“golang.org/x/oauth2”向 facebook 进行身份验证:“缺少 redirect_uri 参数”
【发布时间】:2016-04-17 11:35:54
【问题描述】:

此代码有效:

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":"Missing redirect_uri 参数。","type":"OAuthException","code":191,"fbtrace_id":"XXXX"}}'

golang.org/x/oauth2 是否无法将code 换成token

【问题讨论】:

    标签: facebook go oauth-2.0 google-oauth


    【解决方案1】:

    我发现了丢失的东西。我显然需要在oauthConfig 结构中添加RedirectURLfield 以使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,
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-13
      • 2015-03-24
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2016-09-04
      相关资源
      最近更新 更多