我尝试使用网页上的Google ID登录。我在控制台中从用户记录了ID_Token。然后,我将其复制并传递给服务器,并试图获取用户信息。但是我在Golang Server中遇到了一个错误
err is oauth2:无法获取令牌:400不良请求 回复: { "错误":" 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()); // Don't send this directly to your server!
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());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
您收到的id_token
已经包含所需用户的信息。
请参阅https://jwt.io找到一个GO库来解码您的令牌。