dongtingrun4973 2016-04-17 02:38
浏览 324
已采纳

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

This code works:

func handleFacebookCallback(w http.ResponseWriter, r *http.Request) {
    state := r.FormValue("state")
    if state != oauthStateString {
        fmt.Printf("invalid oauth state, expected '%s', got '%s'
", 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
", err)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }
    defer resp.Body.Close()

But when I replace the part below the marker //////... with:

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

I get:

oauthConf.Exchange() failed with 'oauth2: cannot fetch token: 400 Bad Request Response: {"error":{"message":"Missing redirect_uri parameter.","type":"OAuthException","code":191,"fbtrace_id":"XXXX"}}'

Is the package golang.org/x/oauth2 unable to exchange a code for a token?

  • 写回答

1条回答 默认 最新

  • dongwei6700 2016-04-17 03:27
    关注

    I found out what was missing. I apparently need to add the RedirectURLfield in the oauthConfig struct to get Exchange() to work properly. This is not the case for Slack or GitHub but apparently FB is slightly more picky.

    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,
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?