亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過google idToken獲取userInfo

如何通過google idToken獲取userInfo

Go
滄海一幻覺 2023-03-29 15:16:22
現在我有一個 google Idtoken,我想通過令牌獲取用戶信息,從這個頁面我找到了如何驗證和獲取 tokenInfo,在 Go 中驗證 Google 登錄 ID 令牌 ,但 tokenInfo 不包含用戶圖片。我應該怎么做才能獲取用戶信息?
查看完整描述

1 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

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": "[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"

}

然后我得到了照片。


查看完整回答
反對 回復 2023-03-29
  • 1 回答
  • 0 關注
  • 430 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號