登录
首页 >  Golang >  Go问答

使用 golang.org/x/oauth2 的 golang Facebook 身份验证

来源:Golang技术栈

时间:2023-04-26 13:59:29 314浏览 收藏

从现在开始,努力学习吧!本文《使用 golang.org/x/oauth2 的 golang Facebook 身份验证》主要讲解了golang等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我正在尝试使用该golang.org/x/oauth2包编写一个简单的程序。但我似乎无法用代码交换访问令牌。以下错误有点误导,因为它表示已使用授权代码,但每次调用登录对话框时都会看到一个新代码。我是golang的新手,我可能会犯一个基本的错误,任何指针都会很有帮助:)

    clientOptions, err = oauth2.New(
        oauth2.Client("xxxxxx", "22222222222222"),
        oauth2.RedirectURL("http://localhost:3000/auth/cb/fb2"),
        oauth2.Scope("public_profile", "email", "user_friends"),
        oauth2.Endpoint(
            "https://www.facebook.com/dialog/oauth",
            "https://graph.facebook.com/oauth/access_token",
        ),
    )

func handleFBSetupOauth(w http.ResponseWriter, r *http.Request) {
    url := clientOptions.AuthCodeURL("state", "online", "auto")
    fmt.Printf("Visit the URL for the auth dialog: %v", url)

    http.Redirect(w, r, url, http.StatusFound)
}

func handleFBOauthCB(w http.ResponseWriter, r *http.Request) (int, string) {
    var err error

    code := r.FormValue("code")
    if code == "" {
        return 500, "No code!"
    }

    fmt.Printf("code - %s", code)

    t, err := clientOptions.NewTransportFromCode(code)
    if err != nil {
        log.Fatal(err)
    }

    client := http.Client{Transport: t}

    url := "https://graph.facebook.com/oauth/access_token?client_id=xxxxxxx&redirect_uri=http://localhost:3000/auth/cb/fb2&client_secret=22222222&code=" + code + ""

    resp, err := client.Get(url)

我从上次获取请求中收到以下错误 -

{"error":{"message":"此授权码已被使用。","type":"OAuthException","code":100}}

我正在遵循这 2 个指南 - Facebook 登录流程 - [https://developers.facebook.com/docs/facebook- login/manually-build-a-login- flow/v2.2](https://developers.facebook.com/docs/facebook-login/manually-build- a-login-flow/v2.2)

最新的 goauth 文档 - https://godoc.org/golang.org/x/oauth2

正确答案

这是一个简单的示例,可以帮助您入门:

package main

import (
  "fmt"
  "io/ioutil"
  "log"
  "net/http"
  "net/url"
  "strings"

  "golang.org/x/oauth2"
  "golang.org/x/oauth2/facebook"
)

var (
  oauthConf = &oauth2.Config{
    ClientID:     "YOUR_CLIENT_ID",
    ClientSecret: "YOUR_CLIENT_SECRET",
    RedirectURL:  "YOUR_REDIRECT_URL_CALLBACK",
    Scopes:       []string{"public_profile"},
    Endpoint:     facebook.Endpoint,
  }
  oauthStateString = "thisshouldberandom"
)

const htmlIndex = `
Logged in with facebook

`

func handleMain(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "text/html; charset=utf-8")
  w.WriteHeader(http.StatusOK)
  w.Write([]byte(htmlIndex))
}

func handleFacebookLogin(w http.ResponseWriter, r *http.Request) {
  Url, err := url.Parse(oauthConf.Endpoint.AuthURL)
  if err != nil {
    log.Fatal("Parse: ", err)
  }
  parameters := url.Values{}
  parameters.Add("client_id", oauthConf.ClientID)
  parameters.Add("scope", strings.Join(oauthConf.Scopes, " "))
  parameters.Add("redirect_uri", oauthConf.RedirectURL)
  parameters.Add("response_type", "code")
  parameters.Add("state", oauthStateString)
  Url.RawQuery = parameters.Encode()
  url := Url.String()
  http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

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")

  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
  }

  resp, err := http.Get("https://graph.facebook.com/me?access_token=" +
    url.QueryEscape(token.AccessToken))
  if err != nil {
    fmt.Printf("Get: %s\n", err)
    http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
    return
  }
  defer resp.Body.Close()

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

  log.Printf("parseResponseBody: %s\n", string(response))

  http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}

func main() {
  http.HandleFunc("/", handleMain)
  http.HandleFunc("/login", handleFacebookLogin)
  http.HandleFunc("/oauth2callback", handleFacebookCallback)
  fmt.Print("Started running on http://localhost:9090\n")
  log.Fatal(http.ListenAndServe(":9090", nil))
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>