oauth-2.0 将Google人员API与服务帐户一起使用

siotufzp  于 2022-10-31  发布在  Go
关注(0)|答案(2)|浏览(219)

我正在使用Google People API访问我的联系人。
我在Google Developers Console中激活了它,并创建了一个项目、一个服务帐户(以....iam.gserviceaccount.com结尾)和一个以JSON格式存储的身份验证密钥。
当我访问联系人时,它似乎采取了我的服务帐户地址的联系人,而不是我的谷歌帐户,这导致了一个空列表。
我如何告诉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: {}
col17t5w

col17t5w1#

服务帐户是不是您服务帐户是虚拟用户它有自己的google drive帐户、google日历和google联系人。您看到空结果集的原因是您没有向服务帐户添加任何联系人。
服务账户通常被用来授权访问开发者拥有的数据。例如,你可以把服务账户的电子邮件地址和你在google drive上的一个文件夹共享,然后它就可以访问你google drive账户上的那个文件夹。你也可以用google calendar做同样的事情。
有一些API不能给予你与其他用户分享你的数据,Youtube,adwords,blogger和谷歌联系人仅举几例。
你不能使用服务帐户来访问你的个人google联系人。你最好的办法是用oauth2来验证你的应用程序,然后通过这种方式来访问它们。

关于Google工作区的注意事项

如果您有一个google工作区帐户,则可以配置一个服务帐户来代表域中的用户,但只能代表域中的用户。Perform Google Workspace domain-wide delegation of authority

zf9nrax1

zf9nrax12#

我不是PythonMaven,但我刚刚在.NET中执行了OP所讨论的任务,我非常肯定它在Python中也是可行的。
因此,看起来所有需要做的就是将域范围的权限委派给SA。即,为您的SA分配所需的作用域,在我的示例中是https://www.googleapis.com/auth/contacts.readonly
然后,您应该执行调用并指定一个尝试模拟的帐户(此处以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中对我很有效。

相关问题