【问题标题】:How to get userInfo through google idToken如何通过google idToken获取userInfo
【发布时间】:2019-02-05 00:25:10
【问题描述】:

现在我有一个google Idtoken,我想通过token获取用户信息, 从这个页面我发现了如何验证和获取tokenInfo, Validating Google sign in ID token in Go 但 tokenInfo 不包含用户图片。 如何获取用户信息?

【问题讨论】:

标签: go google-api google-oauth


【解决方案1】:

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,将payload解码为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"
}

然后我得到图片。

【讨论】:

  • 这行得通。将jwt.StandardClaims 添加到type TokenInfo struct 是关键。
猜你喜欢
  • 2020-04-16
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 2020-10-19
  • 2013-09-07
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
相关资源
最近更新 更多