通过服务帐户使用 Google 人 API

Using Google People API with Service Account

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

我在 Google 开发人员控制台中激活了它并创建了一个项目、一个服务帐户(以 ....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: {}

服务帐户不是你服务帐户是虚拟用户它有自己的google驱动器帐户,google日历,显然google 联系人。您看到空结果集的原因是您没有向服务帐户帐户添加任何联系人。

服务帐户最常用于授予对开发人员拥有的数据的访问权限。例如,您可以获取服务帐户电子邮件地址并在 google 驱动器上共享您的一个文件夹,然后它将可以访问您的 google 驱动器帐户上的该文件夹。您可以对 google 日历执行相同的操作。

有一些 API 不允许您与其他用户共享您的数据。 Youtube、adwords、博客和 google 联系人等等。

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

不是 python 专家,但我刚刚执行了 OP 在 .NET 中谈论的任务,我很确定 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 中为我工作。