猿问

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

此代码有效:


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 parameter.","type":"OAuthException","code":191, "fbtrace_id":"XXXX"}}'


包裹是否golang.org/x/oauth2无法将 a 换成codea token?


杨__羊羊
浏览 302回答 1
1回答

jeck猫

我发现缺少了什么。我显然需要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,    }
随时随地看视频慕课网APP

相关分类

Go
我要回答