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

huangapple go评论84阅读模式
英文:

Authenticating with oauth2 using package "golang.org/x/oauth2"

问题

我正在尝试弄清楚如何使用golang.org/x/oauth2包来对支持oauth2的网站进行身份验证。

我写的下面的代码是有效的,我只是想知道这是否是正确的方法,使用这个特定的库来获取一个*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'\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
    }

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

    tc := oauth2.NewClient(oauth2.NoContext, ts) // got *http.Client
}

请注意,这只是一个示例代码,具体的实现可能因你的需求而有所不同。

英文:

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'\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
	}

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

	tc := oauth2.NewClient(oauth2.NoContext, ts) // got *http.Client

答案1

得分: 0

跟进:我已经使用并多次调整过它,它能完成任务。

英文:

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

huangapple
  • 本文由 发表于 2016年4月17日 09:27:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/36671719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定