1

我正在尝试使用服务帐户来访问组的成员。我已经验证我可以代表用户使用普通的 OAuth2 令牌执行此操作,并调用 tohttps://www.googleapis.com/admin/directory/v1/groups/{group}/members和 scope 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"
 }
}

我需要做什么才能授权此服务帐户查看该组?

4

2 回答 2

0

您可以按照以下 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();
于 2015-06-11T15:31:46.793 回答
0

假设你有以下

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)

这个答案的真相来源在这里

于 2020-07-18T01:01:04.023 回答