wkzq
wkzq

Reputation: 333

How to get userInfo through google idToken

Now I hava a google Idtoken, I want to get the user information through the token, from this page I found how to verify and get the tokenInfo, Validating Google sign in ID token in Go but the tokenInfo doesn't contain user picture. what should I do to get the user information?

Upvotes: 3

Views: 3341

Answers (1)

wkzq
wkzq

Reputation: 333

id_token is a jwt. I first use validating-google-sign-in-id-token-in-go to check the token is vailed.

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
}

Then I parse the id_token as jwt, decode the payload to 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
}

the value like:

{
 // 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": "[email protected]",
 "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"
}

then I get the picture.

Upvotes: 2

Related Questions