doucai7294
2016-04-17 01:27
浏览 409
已采纳

使用软件包“ golang.org/x/oauth2”对oauth2进行身份验证

I am trying to figure out how I can use the package golang.org/x/oauth2 to authenticate on a site supporting oauth2.

The code I wrote below works, I am just curious if this is the right approach, using this particular library, to obtain an *http.Client:

func handleCallback(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")
    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
    }

    ts := oauth2.StaticTokenSource(
        &oauth2.Token{AccessToken: token.AccessToken},
    )

    tc := oauth2.NewClient(oauth2.NoContext, ts) // got *http.Client
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyun1852 2016-12-24 20:26
    已采纳

    Follow up: I've used it and tweaked it several times and it does the job.

    打赏 评论

相关推荐 更多相似问题