go - 如何通过google idToken获取userInfo
问题描述
现在我有一个 google Idtoken,我想通过令牌获取用户信息,从这个页面我找到了如何验证和获取 tokenInfo, 在 Go 中验证 Google 登录 ID 令牌, 但 tokenInfo 不包含用户图片。我应该怎么做才能获取用户信息?
解决方案
id_token 是一个 jwt。我首先使用validating-google-sign-in-id-token-in-go来检查令牌是否有效。
authService, err := oauth2.New(http.DefaultClient)
if err != nil {
return err
}
// check token is valid
tokenInfoCall := authService.Tokeninfo()
tokenInfoCall.IdToken(idToken)
ctx, cancelFunc := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancelFunc()
tokenInfoCall.Context(ctx)
tokenInfo, er := tokenInfoCall.Do()
if err != nil {
// invalid token
}
然后我将 id_token 解析为 jwt,将有效负载解码为 json。
token, _, err := new(jwt.Parser).ParseUnverified(idToken, &TokenInfo{})
if tokenInfo, ok := token.Claims.(*TokenInfo); ok {
return tokenInfo, nil
} else {
// parse token.payload failed
}
// TokenInfo struct
type TokenInfo struct {
Iss string `json:"iss"`
// userId
Sub string `json:"sub"`
Azp string `json:"azp"`
// clientId
Aud string `json:"aud"`
Iat int64 `json:"iat"`
// expired time
Exp int64 `json:"exp"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
AtHash string `json:"at_hash"`
Name string `json:"name"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Picture string `json:"picture"`
Local string `json:"locale"`
jwt.StandardClaims
}
像这样的值:
{
// These six fields are included in all Google ID Tokens.
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953",
// These seven fields are only included when the user has granted the "profile" and
// "email" OAuth scopes to the application.
"email": "testuser@gmail.com",
"email_verified": "true",
"name" : "Test User",
"picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
"given_name": "Test",
"family_name": "User",
"locale": "en"
}
然后我得到了图片。
推荐阅读
- javascript - 如何通过ajax将xml文件数据发送到Webmethod?
- iis - IIS 10 URL 将 http 流量重写为 https 重定向不起作用
- javascript - 在“动态”画布上绘图
- arduino - ESP32 上的 AsyncTCP 和带有 SOFTAP 的奇怪堆/套接字问题
- python - 为什么 json 似乎无法正确处理具有相当大数据的对象
- django - 不需要外键
- r - 排名与并列数字
- css - 带有 CSS 的 tabsetPanel 样式(不止一种样式),R Shiny
- powershell - 使用 Powershell 恢复 SSRS/PowerBI 报告服务器加密密钥
- java - 如何在 Java 中为 Java 8 Predicate 和 distinctByKeys 编写 Mockito 测试