英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论