我正在尝试使用服务帐户访问组的成员。我已经验证了我可以使用代表用户的普通OAuth2令牌,调用https://www.googleapis.com/admin/directory/v1/groups/{group}/members
和范围https://www.googleapis.com/auth/admin.directory.group.readonly
来做到这一点。
我想对服务帐户做同样的事情,我已经将服务帐户的电子邮件地址添加为组成员,并验证View Members权限设置为"组的所有成员,所有组织成员"。
当我请求一个成员列表时,我收到这个错误:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Not Authorized to access this resource/api"
}
],
"code": 403,
"message": "Not Authorized to access this resource/api"
}
}
我需要做什么才能授权此服务帐户查看组?
假设您有以下内容
- 服务的路径-account-key. json
- 在服务eaccount 上启用域范围委托
-
admin email id
业务账号通过域授权,可以使用admin邮箱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)
答案的真实来源在这里
您可以按照以下API文档页面中概述的步骤创建服务帐户并执行域范围的权限委托,请记住您需要组成员的任何用户的电子邮件地址(userEmail在下面的代码片段中),以便服务帐户可以代表他们行事:
https://developers.google.com/admin-sdk/directory/v1/guides/delegation该页面包含一个Java和Python示例,说明如何使用在Google Developers Console
上创建的服务帐户和私钥实例化com.google.api.services.admin.directory.Directory对象。 GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(DirectoryScopes.ADMIN_DIRECTORY_USERS)
.setServiceAccountUser(userEmail)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();