can't get user profile info using Oauth2 in server using id_token provided by client

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

can't get user profile info using Oauth2 in server using id_token provided by client

问题

我尝试使用Google ID在我的网页上登录。我在控制台中记录了用户的id_token。然后我将其复制并传递给服务器,尝试获取用户信息。但是在Golang服务器中出现错误:

> 错误是oauth2: 无法获取令牌:400 Bad Request
响应:{
"error" : "invalid_grant"
}

这是我的服务器端代码。

func main() {
	go func() {
		http.ListenAndServe(":8123", nil)
	}()
	http.HandleFunc("/", serveFile)
	http.HandleFunc("/loginUser", loginUser)
	<-quit
}

func loginUser(rw http.ResponseWriter, req *http.Request) {
	id_token, _ := getIdToken(req)
	conf := oauth2.Config{
		ClientID:     "HIDDEN.apps.googleusercontent.com",
		ClientSecret: "HIDDEN",
		Scopes: []string{
			"https://www.googleapis.com/auth/userinfo.email",
			"https://www.googleapis.com/auth/userinfo.profile",
		},
		Endpoint: google.Endpoint,
	}
	L.Errorln(id_token)
	tok, err := conf.Exchange(oauth2.NoContext, id_token)
	if err != nil {
		L.Errorln("err is", err)
	}

	L.Errorln("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)
	L.Errorln(contents, err)
}

这是我的客户端代码。

<!DOCTYPE html>
<html>
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="HIDDEN.apps.googleusercontent.com">
<script src="https://apis.google.com/js/client:platform.js?" async defer></script>
<script  src="/login.js"></script>
<link rel="stylesheet" type="text/css" href="/login.css">
<title>Wander</title>
</head>
<body>
<div id="g-login" class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>

<a href="#" onclick="signOut();">Sign out</a>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
  console.log('User signed out.');
});
}
</script>
</body>
</html>

login.js

function onSignIn(googleUser) {
    // Useful data for your client-side scripts:
    var profile = googleUser.getBasicProfile();
    console.log("ID: " + profile.getId()); // 不要直接发送给服务器!
    console.log('Full Name: ' + profile.getName());
    console.log('Given Name: ' + profile.getGivenName());
    console.log('Family Name: ' + profile.getFamilyName());
    console.log("Image URL: " + profile.getImageUrl());
    console.log("Email: " + profile.getEmail());

    // 需要传递给后端的ID令牌:
    var id_token = googleUser.getAuthResponse().id_token;

    console.log("ID Token: " + id_token);
};

希望这些信息对你有帮助!

英文:

I tried to log in using the google id on my web page. I logged the id_token from the user in console. Then I copied that and passed to a server and tried to get user info. But I get an error in golang server as

> err is oauth2: cannot fetch token: 400 Bad Request
Response: {
"error" : "invalid_grant"
}

This is my serve side code.

func main() {
go func() {
	http.ListenAndServe(&quot;:8123&quot;, nil)
}()
http.HandleFunc(&quot;/&quot;, serveFile)
http.HandleFunc(&quot;/loginUser&quot;, loginUser)
&lt;-quit
}
func loginUser(rw http.ResponseWriter, req *http.Request) {
id_token, _ := getIdToken(req)
conf := oauth2.Config{
	ClientID:     &quot;HIDDEN.apps.googleusercontent.com&quot;,
	ClientSecret: &quot;HIDDEN&quot;,
	Scopes: []string{
		&quot;https://www.googleapis.com/auth/userinfo.email&quot;,
		&quot;https://www.googleapis.com/auth/userinfo.profile&quot;,
	},
	Endpoint: google.Endpoint,
}
L.Errorln(id_token)
tok, err := conf.Exchange(oauth2.NoContext, id_token)
if err != nil {
	L.Errorln(&quot;err is&quot;, err)
}

L.Errorln(&quot;token is &quot;, tok)
response, err := http.Get(&quot;https://www.googleapis.com/oauth2/v2/userinfo?access_token=&quot; + tok.AccessToken)

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

My client side code as follows

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta name=&quot;google-signin-scope&quot; content=&quot;profile email&quot;&gt;
&lt;meta name=&quot;google-signin-client_id&quot; content=&quot;HIDDEN.apps.googleusercontent.com&quot;&gt;
 &lt;script src=&quot;https://apis.google.com/js/client:platform.js?&quot; async defer&gt;
 &lt;/script&gt;
 &lt;script  src=&quot;/login.js&quot;&gt;&lt;/script&gt;
 &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;/login.css&quot;&gt;
 &lt;title&gt;Wander&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
 &lt;div id=&quot;g-login&quot; class=&quot;g-signin2&quot; data-onsuccess=&quot;onSignIn&quot; data-
 theme=&quot;dark&quot; &gt;&lt;/div&gt;

&lt;a href=&quot;#&quot; onclick=&quot;signOut();&quot;&gt;Sign out&lt;/a&gt;
&lt;script&gt;
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
  console.log(&#39;User signed out.&#39;);
});
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

login.js

    function onSignIn(googleUser) {
    // Useful data for your client-side scripts:
    var profile = googleUser.getBasicProfile();
    console.log(&quot;ID: &quot; + profile.getId()); // Don&#39;t send this directly to your server!
    console.log(&#39;Full Name: &#39; + profile.getName());
    console.log(&#39;Given Name: &#39; + profile.getGivenName());
    console.log(&#39;Family Name: &#39; + profile.getFamilyName());
    console.log(&quot;Image URL: &quot; + profile.getImageUrl());
    console.log(&quot;Email: &quot; + profile.getEmail());

    // The ID token you need to pass to your backend:
    var id_token = googleUser.getAuthResponse().id_token;

    console.log(&quot;ID Token: &quot; + id_token);
};

答案1

得分: 1

你收到的id_token已经包含了你所需的用户信息。

请访问https://jwt.io查找一个Go库来解码你的令牌。

英文:

The id_token you received already contains the information of the user you need.

See https://jwt.io to find a Go library to decode your token.

huangapple
  • 本文由 发表于 2017年4月30日 20:16:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/43706248.html
匿名

发表评论

匿名网友

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

确定