我有以下 JavaScript 代码
auth2.grantOfflineAccess().then(function(codeData) {
if (!codeData) {
alert("Something went wrong");
return;
}
$.post("/do/signIn/google", codeData, function() { ... });
});
我正在将 Google 登录代码发送到我的 golang 网络应用程序。
我从 POST https://www.googleapis.com/oauth2/v4/token
成功获得了访问 token 。
我的问题是,我无法获取用户的个人资料信息(例如电子邮件、显示名称等)
我尝试发送请求到 GET https://www.googleapis.com/auth/userinfo.profile?access_token=xxx
,但我收到了一个空响应(空白正文)。
最佳答案
您必须对 POST https://www.googleapis.com/oauth2/v4/token
返回的 Google ID token 进行解码,以将其转换为 Google+ ID,然后您可以使用 GET https://www.googleapis.com/plus/v1/people/[gplusID]?access_token=[accessToken]
Using Go, you can decode the google ID token using the following function. Normally, it is critical that you validate an ID token before you use it, but since you are communicating directly with Google over an intermediary-free HTTPS channel and using your Client Secret to authenticate yourself to Google, you can be confident that the token you receive really comes from Google and is valid. If your server passes the ID token to other components of your app, it is extremely important that the other components validate the token before using it.
使用 Go,您可以使用以下函数解码 ID token 。
func decodeGoogleIDToken(idToken string) (gplusID string, err error) {
var set struct {
Sub string
}
if idToken != "" {
// Check that the padding is correct for a base64decode
parts := strings.Split(idToken, ".")
if len(parts) < 2 {
return "", fmt.Errorf("Malformed ID token")
}
// Decode the ID token
s := parts[1]
switch len(s) % 4 {
case 2:
s += "=="
case 3:
s += "="
}
b, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return "", fmt.Errorf("Malformed ID token: %v", err)
}
err = json.Unmarshal(b, &set)
if err != nil {
return "", fmt.Errorf("Malformed ID token: %v", err)
}
}
return set.Sub, nil
}
关于go - 从访问 token 获取 Google 登录个人资料信息 - Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339163/