【问题标题】:Golang google client api, how to get the user information with `Userinfo` structGolang google客户端api,如何使用`Userinfo`结构获取用户信息
【发布时间】:2022-09-27 09:21:44
【问题描述】:

我目前正在使用 Golang 构建一个后端 Rest API 来处理来自移动应用程序的 HTTP 请求。我现在正在实现的功能之一是使用外部提供商(例如 Google、Apple 等)进行注册/登录。

对于谷歌,我已经阅读了这篇关于如何authenticate with a backend server 的文章。主要思想是通过 POST 端点向后端发送令牌 id 并验证令牌的内容。验证令牌后,我可以从后端检索用户信息并创建一个帐户(如果它不存在)。

到目前为止,使用 oath2 Golang 包,我可以像这样验证令牌:

func verifyIdToken(idToken string) error {
    ctx := context.Background()
    oauth2Service, err := oauth2.NewService(ctx, option.WithoutAuthentication())

    if err != nil {
        return err
    }

    tokenInfoCall := oauth2Service.Tokeninfo()
    tokenInfoCall.IdToken(idToken)

    tokenInfo, err := tokenInfoCall.Do()

    if err != nil {
        e, _ := err.(*googleapi.Error)
        return e
    }
    fmt.Println(tokenInfo.Email)
    return nil
}

请注意:要获取令牌 ID,我使用的是 Oauth playground,并设置了以下范围:

https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile
opened

在搜索oauth2 后,我注意到一个类型UserInfo 包含我需要的所有信息。但是,tokenInfo 对象不会返回来自用户的所有信息,例如名字和姓氏。但是,我在如何获取 UserInfo 上遇到了一些困难。

简而言之,我创建了一个名为 getUserInfo 的函数,如下所示:

func getUserInfo(service *oauth2.Service) (*oauth2.Userinfo, error) {
    userInfoService := oauth2.NewUserinfoV2MeService(service)

    userInfo, err := userInfoService.Get().Do()

    if err != nil {
        e, _ := err.(*googleapi.Error)
        fmt.Println(e.Message)
        return nil, e
    }
    return userInfo, nil
}

注意:我在verifyIdToken 中调用了getUserInfo userInfo, err := getUserInfo(oauth2Service)

但是,我总是收到这个 401 错误:

googleapi: Error 401: Request is missing required authentication credential. 
Expected OAuth 2 access token, login cookie or other valid authentication credential. 
See https://developers.google.com/identity/sign-in/web/devconsole-project., 
unauthorized

有了这个,我不知道该怎么办。

    标签: go google-oauth


    【解决方案1】:

    我想你已经找到了你问题的答案很长时间了,但我仍然把我的解决方案留在这里。

    用户信息服务实际上并没有在里面传递一个令牌。为此,您可以使用如下代码:

    import  "google.golang.org/api/googleapi"
    
        token := "ya29.a0Aa4xrXMAp..." 
        userInfo, err := userInfoService.Get().Do(googleapi.QueryParameter("access_token", token))
        if err != nil {
            e, _ := err.(*googleapi.Error)
            fmt.Println(e.Message)
            return nil, e
        }
    

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 2016-04-12
      • 1970-01-01
      • 2018-12-21
      • 2020-03-22
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多