【问题标题】:Using Google People API with Service Account将 Google People API 与服务帐户一起使用
【发布时间】:2018-08-10 09:57:00
【问题描述】:

我正在使用 Google People API 访问我的联系人。

我在 Google Developers Console 中激活它并创建了一个项目、一个服务帐户(以 ....iam.gserviceaccount.com 结尾)和一个以 JSON 格式存储的身份验证密钥。

当我访问联系人时,它似乎使用了我的服务帐户地址而不是我的 Google 帐户的联系人,这导致列表为空。

如何告诉 API 使用我的帐户而不是服务帐户?

这是我目前的代码:

from google.oauth2 import service_account
from googleapiclient.discovery import build
# pip install google-auth google-auth-httplib2 google-api-python-client

SCOPES = ['https://www.googleapis.com/auth/contacts.readonly']
KEY = '~/private.json'

credentials = service_account.Credentials.from_service_account_file(
    KEY, scopes=SCOPES)
service = build(
    serviceName='people', version='v1', credentials=credentials)
connections = service.people().connections().list(
    resourceName='people/me', personFields='names').execute()

print(connections)
# result: {}

【问题讨论】:

    标签: python oauth-2.0 google-api google-api-python-client google-people-api


    【解决方案1】:

    服务帐户不是您服务帐户是虚拟用户,它有自己的谷歌驱动器帐户、谷歌日历和显然的谷歌联系人。您看到空结果集的原因是您尚未将任何联系人添加到服务帐户帐户。

    服务帐号最常用于授予对开发者拥有的数据的访问权限。例如,您可以使用服务帐户电子邮件地址并在 google drive 上共享您的一个文件夹,然后它就可以访问您的 google drive 帐户上的该文件夹。你可以用谷歌日历做同样的事情。

    有些 API 无法让您与其他用户共享您的数据。 Youtube、adwords、博主和谷歌联系人等等。

    您不能使用服务帐户访问您的个人 Google 联系人。您最好的选择是使用 oauth2 验证您的应用程序并以这种方式访问​​它们。

    【讨论】:

      【解决方案2】:

      我不是 python 专家,但我刚刚在 .NET 中执行了 OP 所说的任务,我很确定它在 Python 中也是可行的。

      所以看起来所有需要做的就是delegating domain-wide authority to the SA。 IE。为您的 SA 分配所需的范围,在我的例子中是 https://www.googleapis.com/auth/contacts.readonly

      然后您应该拨打电话并指定您要模拟的帐户(从here 获取 python 示例)

      from google.oauth2 import service_account
      
      SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
      SERVICE_ACCOUNT_FILE = '/path/to/service.json'
      
      credentials = service_account.Credentials.from_service_account_file(
              SERVICE_ACCOUNT_FILE, scopes=SCOPES)
      
      # this is the line you apparently were missing
      delegated_credentials = credentials.with_subject('user@example.org')
      

      然后您就可以拨打people/me 了。正如我所说,在 .NET 中为我工作。

      【讨论】:

        猜你喜欢
        • 2020-06-09
        • 2014-10-15
        • 1970-01-01
        • 1970-01-01
        • 2014-10-01
        • 2019-11-26
        • 2016-08-11
        • 1970-01-01
        • 2012-09-13
        相关资源
        最近更新 更多