7

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

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

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

我在这里发现了一些有趣的东西:有没有办法在使用 Oauth 对 Gmail 进行身份验证后获取您的电子邮件地址?

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

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

女巫返回对两种服务都有效的无效...有什么想法吗?

4

2 回答 2

13

我只想添加一个我发现特别容易使用的资源。这是:链接。Kallsbo 通过搜索 scope 将我引导到正确的位置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'],你已经有你的电子邮件了!:)

于 2014-10-20T09:15:41.873 回答
8

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

请求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/

于 2013-10-21T03:53:18.640 回答