我正在尝试使用服务帐户访问群组成员。我已经验证我可以代表用户使用普通的 OAuth2 token 执行此操作,并调用 https://www.googleapis.com/admin/directory/v1/groups/{group}/members
和范围 https://www.googleapis.com/auth/admin.directory.group.readonly
。
我想对服务帐户执行相同操作,我已将服务帐户电子邮件地址添加为群组成员,并确认查看成员权限设置为“所有成员”组,所有组织成员”。
当我请求成员列表时,我收到此错误:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Not Authorized to access this resource/api"
}
],
"code": 403,
"message": "Not Authorized to access this resource/api"
}
}
我需要做什么才能授权此服务帐户查看群组?
最佳答案
假设您有以下内容
- 您的 serivce-account-key.josn 的路径
- Domain wide delegation enabled on the service eaccount
admin email id
由于全域委派,服务帐户可以使用管理员电子邮件 id。
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ["https://www.googleapis.com/auth/admin.directory.user",
"https://www.googleapis.com/auth/admin.directory.group"]
credentials = service_account.Credentials.from_service_account_file(
PATH-TO-YOUR-SERVICE-ACCOUNT-FILE,
scopes=SCOPES, subject=ADMIN-EMAIL-ID)
service = build('admin', 'directory_v1', credentials=credentials)
group = "YOUR-GROUP-EMAIL-ID"
direct_members = service.members().list(groupKey=group).execute()["members"]
print(direct_members)
# Note that the above code would give only direct members.
# To get the direct members, set the `inclueDerivedMembership`
# argument to True as below.
all_members = service.members().list(
groupKey=group, inclueDerivedMembership=True).execute()["members"]
print(all_members)
这个答案的真实来源是here .
关于service-accounts - 如何使用服务帐户访问群组成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30763840/