golang google oauth2 – 无法获取用户信息(库:https://github.com/golang/oauth2)

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

golang google oauth2 - not able to get user info (library : https://github.com/golang/oauth2)

问题

我正在使用以下库进行Google OAuth2的身份验证:https://github.com/golang/oauth2

我正在使用示例中提供的代码(链接:http://play.golang.org/p/qXyuaVEhyS,https://godoc.org/golang.org/x/oauth2/google)

我能够获取授权代码和令牌,但无法进行获取用户信息的GET请求。

我的代码:

conf := &oauth2.Config{
    ClientID:     "我的客户端ID",
    ClientSecret: "秘密ID",
    RedirectURL:  "http://localhost:3000/googlelogin",
    Scopes: []string{
        "https://www.googleapis.com/auth/userinfo.profile",
    },
    Endpoint: google.Endpoint,
}

m.Get("/googleloginrequest", func(r render.Render, request *http.Request) {

    url := conf.AuthCodeURL("state")
    fmt.Printf("访问以下URL以进行授权对话框: %v", url)

    r.Redirect(url)

})

m.Get("/googlelogin", func(r render.Render, request *http.Request) {

    authcode := request.FormValue("code")

    tok, err := conf.Exchange(oauth2.NoContext, authcode)
    if err != nil {
        log.Fatal(err)
    }

    client := conf.Client(oauth2.NoContext, tok)

    resp, err :=client.Get("https://www.googleapis.com/userinfo/v2/me")

    r.JSON(200, map[string]interface{}{"status":resp})
})

我在这里得到的响应非常庞大,没有任何用户信息。

响应:

200 OK","StatusCode":200,"Proto":"HTTP/1.1","ProtoMajor":1,"ProtoMinor":1,"Header":{"Alternate-

Protocol":["443:quic,p=0.02"],"Cache-Control":["no-cache, no-store, max-age=0, must-
revalidate"],"Content-Type":["application/json; charset=UTF-8"],"Date":["Tue, 23 Dec 2014 18:18:19
GMT"],"Expires":["Fri, 01 Jan 1990 00:00:00 GMT"],"Pragma":["no-cache"],"Server":["GSE"],"Vary":
["Origin","X-Origin"],"X-Content-Type-Options":["nosniff"],"X-Frame-Options":["SAMEORIGIN"],"X-Xss-
Protection":["1; mode=block"]},"Body":{},"ContentLength":-1,"TransferEncoding":
["chunked"],"Close":false,"Trailer":null,"Request":{"Method":"GET","URL":
{"Scheme":"https","Opaque":"","User":null,"Host":"www.googleapis.com","Path":"/userinfo/v2/me","RawQuery
":"","Fragment":""},"Proto":"HTTP/1.1","ProtoMajor":1,"ProtoMinor":1,"Header":{"Authorization":["Bearer
ya29.5QDPWWRKB7tNkdB2Yvm0PCST9LF_iQhjN1Y0g2abE-
lnw9BNgEd_n3A85ZfJzDNYZywqqElCb7Z2xA"]},"Body":null,"ContentLength":0,"TransferEncoding":null,"Close":fa
lse,"Host":"www.googleapis.com","Form":null,"PostForm":null,"MultipartForm":null,"Trailer":null,"RemoteA
ddr":"","RequestURI":"","TLS":null},"TLS":{"Version":771,"HandshakeComplete":true,"DidResume":false,
....

请帮助我,或者建议其他适用于上述情况的可行库/代码。

英文:

i am using the following library for google oauth2 https://github.com/golang/oauth2

I am using the code given in the examples (url : http://play.golang.org/p/qXyuaVEhyS ,https://godoc.org/golang.org/x/oauth2/google )

I am able to get the auth code and token , but not able to make a get request to get user info

MyCode :

conf := &oauth2.Config{
		ClientID:     "my client id",
		ClientSecret: "secred id",
		RedirectURL:  "http://localhost:3000/googlelogin",
		Scopes: []string{
			"https://www.googleapis.com/auth/userinfo.profile",
		},
		Endpoint: google.Endpoint,
	}

m.Get("/googleloginrequest", func(r render.Render, request *http.Request) {

	url := conf.AuthCodeURL("state")
	fmt.Printf("Visit the URL for the auth dialog: %v", url)

	r.Redirect(url)

})

m.Get("/googlelogin", func(r render.Render, request *http.Request) {

		authcode := request.FormValue("code")

		tok, err := conf.Exchange(oauth2.NoContext, authcode)
		if err != nil {
			log.Fatal(err)
		}
		
		client := conf.Client(oauth2.NoContext, tok)

		resp, err :=client.Get("https://www.googleapis.com/userinfo/v2/me")
		
		r.JSON(200, map[string]interface{}{"status":resp})
	})

the response i get here is very big and does not have any user info

response :

 200 OK","StatusCode":200,"Proto":"HTTP/1.1","ProtoMajor":1,"ProtoMinor":1,"Header":{"Alternate-
Protocol":["443:quic,p=0.02"],"Cache-Control":["no-cache, no-store, max-age=0, must-
revalidate"],"Content-Type":["application/json; charset=UTF-8"],"Date":["Tue, 23 Dec 2014 18:18:19 
    GMT"],"Expires":["Fri, 01 Jan 1990 00:00:00 GMT"],"Pragma":["no-cache"],"Server":["GSE"],"Vary":
    ["Origin","X-Origin"],"X-Content-Type-Options":["nosniff"],"X-Frame-Options":["SAMEORIGIN"],"X-Xss-
    Protection":["1; mode=block"]},"Body":{},"ContentLength":-1,"TransferEncoding":
    ["chunked"],"Close":false,"Trailer":null,"Request":{"Method":"GET","URL":
 {"Scheme":"https","Opaque":"","User":null,"Host":"www.googleapis.com","Path":"/userinfo/v2/me","RawQuery
    ":"","Fragment":""},"Proto":"HTTP/1.1","ProtoMajor":1,"ProtoMinor":1,"Header":{"Authorization":["Bearer 
    ya29.5QDPWWRKB7tNkdB2Yvm0PCST9LF_iQhjN1Y0g2abE-
    lnw9BNgEd_n3A85ZfJzDNYZywqqElCb7Z2xA"]},"Body":null,"ContentLength":0,"TransferEncoding":null,"Close":fa
    lse,"Host":"www.googleapis.com","Form":null,"PostForm":null,"MultipartForm":null,"Trailer":null,"RemoteA
    ddr":"","RequestURI":"","TLS":null},"TLS":{"Version":771,"HandshakeComplete":true,"DidResume":false, 
    ....

Please help, or suggest me other working library/code ,which works in the above scenario

答案1

得分: 10

这个库对我有用 "golang.org/x/oauth2/google"

初始化

googleconf = &oauth2.Config{
ClientID: "your-client-id",
ClientSecret: "youe-secred",
RedirectURL: "http://localhost:300/googlelogin",
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
},
Endpoint: google.Endpoint,
}

重定向用户请求:

url := googleconf.AuthCodeURL("state")
response.Redirect(url)

从Google获取数据:

authcode := request.FormValue("code")

tok, err := googleconf.Exchange(oauth2.NoContext, authcode)
if err != nil {
fmt.Println("err is", err)
}

fmt.Println("token is ", tok)
response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + tok.AccessToken)

defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)

英文:

this Library works for me "golang.org/x/oauth2/google"

Initiatialization

googleconf = &oauth2.Config{
		ClientID:     "your-client-id",
		ClientSecret: "youe-secred",
		RedirectURL:  "http://localhost:300/googlelogin",
		Scopes: []string{
			"https://www.googleapis.com/auth/userinfo.profile",
			"https://www.googleapis.com/auth/userinfo.email",
		},
		Endpoint: google.Endpoint,
	}

Redirect User on Request :

url := googleconf.AuthCodeURL("state")
response.Redirect(url)

Getting Data From Google :

    authcode := request.FormValue("code")

	tok, err := googleconf.Exchange(oauth2.NoContext, authcode)
	if err != nil {
		fmt.Println("err is", err)
	}

	fmt.Println("token is ", tok)
	response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + tok.AccessToken)

    defer response.Body.Close()
    contents, err := ioutil.ReadAll(response.Body)

huangapple
  • 本文由 发表于 2014年12月24日 02:22:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/27625949.html
匿名

发表评论

匿名网友

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

确定