登录
首页 >  Golang >  Go问答

获取用户信息的方法使用Google的idToken

来源:stackoverflow

时间:2024-03-24 08:39:35 407浏览 收藏

通过 Google ID 令牌获取用户信息需要分步进行。首先,验证令牌是否有效。然后,将令牌解析为 JWT 并解码有效负载。最后,提取所需的用户数据,包括电子邮件、姓名和个人资料图片。此过程涉及使用 Google API 客户端库,例如 validating-google-sign-in-id-token-in-go,以及手动解析令牌。

问题内容

现在我有一个google Idtoken,我想通过token获取用户信息, 从这个页面我找到了如何验证和获取 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": "[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"
}

然后我就得到了图片。

今天关于《获取用户信息的方法使用Google的idToken》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>