【问题标题】:How to get user email after OAUTH with Google API Python Client如何在 OAUTH 之后使用 Google API Python 客户端获取用户电子邮件
【发布时间】:2013-10-28 16:33:03
【问题描述】:

我目前正在用 Python 构建一个与 Google API 交互的网络应用。使用 oauth 访问用户资源。像这样成功认证和升级令牌后:

gd_client = gdata.photos.service.PhotosService()
gd_client.SetAuthSubToken(token)
gd_client.UpgradeToSessionToken()

然后我可以访问 API 的不同提要并获取用户的列表,例如 Youtube 视频。但是用户只用谷歌登录,我只有一个 oauth 令牌,没有关于用户的其他信息。如何检索有关用户的信息?像电子邮件、显示名称等?我一直在测试很多不同的东西,但没有设法解决这个问题......

我在这里发现了一些有趣的东西:Is there a way to get your email address after authenticating with Gmail using Oauth?

我的理论是我可以使用 PhotoService.GetAuthSubToken() 然后重用该令牌来请求联系人并从联系人条目中获取 auther.email。将授权范围更改为:

scope = ['https://picasaweb.google.com/data/', 'https://www.google.com/m8/feeds/']

witch 返回一个对两种服务都有效的 roken...有什么想法吗?

【问题讨论】:

    标签: python api oauth


    【解决方案1】:

    我只是想添加一个我发现特别容易使用的资源。这是:link。 Kallsbo 通过搜索范围 https://www.googleapis.com/auth/userinfo.email 将我引导到正确的位置。在您已经拥有credentials 之后,只需使用直接从该链接获取的以下函数:

        def get_user_info(credentials):
      """Send a request to the UserInfo API to retrieve the user's information.
    
      Args:
        credentials: oauth2client.client.OAuth2Credentials instance to authorize the
                     request.
      Returns:
        User information as a dict.
      """
      user_info_service = build(
          serviceName='oauth2', version='v2',
          http=credentials.authorize(httplib2.Http()))
      user_info = None
      try:
        user_info = user_info_service.userinfo().get().execute()
      except errors.HttpError, e:
        logging.error('An error occurred: %s', e)
      if user_info and user_info.get('id'):
        return user_info
      else:
        raise NoUserIdException()
    

    打电话给user_email = get_user_info(credentials)['email'],您的电子邮件已经在那里了! :)

    【讨论】:

    • 是的!非常感谢!这是使用官方 google-api 库的方法。
    【解决方案2】:

    所以我找到了一个很好的方法!

    请求https://www.googleapis.com/auth/userinfo.email 的额外范围,然后我可以使用 Gdata.Client 访问它以获取电子邮件地址。

    完整示例代码:https://code.google.com/p/google-api-oauth-demo/

    完整记录我是如何到达那里的:http://www.hackviking.com/2013/10/python-get-user-info-after-oauth/

    【讨论】:

    • Kristofer,我找这个已经好几天了!非常感谢您发布博客!
    • marty331:很高兴分享它,我花了一段时间阅读,测试和百事可乐才破解它!
    • 伙计,你救了我的命!谢谢!
    猜你喜欢
    • 2020-01-04
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多