如何从App Engine Python访问G Suite目录API?

问题描述

我正在尝试遵循文档,但实际上一直无法访问。理想情况下,我想使用App Engine服务帐户来访问我的域的用户列表,但是我愿意使用一个单独的服务帐户。

  1. 我已经创建了一个服务帐户。
    电子邮件 [email protected]
    ID: 1097...8840

  2. 已为G Suite域范围的委派启用了服务帐户。
    客户端ID: 1097...8840

  3. 在我的域的“安全性”>“ API控件”>“域范围的委派”下,我已添加此服务帐户。
    客户端ID: 1097...8840
    范围: https://www.googleapis.com/auth/admin.directory.user.readonly


尝试使用隐式服务帐户

我正在尝试这种方法,因为我希望可以使用相同的方法来访问App Engine服务帐户。

$ export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"
$ python3
>>> import googleapiclient.discovery 
>>> userapi = googleapiclient.discovery.build('admin','directory_v1')
>>> userapi.users().list(domain='my-domain.com',maxResults=100).execute()

googleapiclient.errors.HttpError: <HttpError 403 when requesting 
https://www.googleapis.com/admin/directory/v1/users?domain=my-domain.com.com&maxResults=100&alt=json
returned "Not Authorized to access this resource/api">

尝试使用明确的服务凭据

在这里,我实际上是在加载凭据,而不是依靠googleapiclient.discovery.build从环境中推断出来:

$ python3
>>> ScopES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
>>> SERVICE_ACCOUNT_FILE = '/path/to/key.json'
>>> from google.oauth2.service_account import Credentials
>>> import googleapiclient.discovery 
>>> credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE,scopes=ScopES)
>>> userapi = googleapiclient.discovery.build('admin','directory_v1',credentials=credentials)
>>> userapi.users().list(domain='my-domain.com',maxResults=100).execute()

googleapiclient.errors.HttpError: <HttpError 403 when requesting 
https://www.googleapis.com/admin/directory/v1/users?domain=my-domain.com.com&maxResults=100&alt=json
returned "Not Authorized to access this resource/api">

我也尝试过不使用domain='my-domain.com位。这给了我这个错误

googleapiclient.errors.HttpError: <HttpError 400 when requesting 
https://www.googleapis.com/admin/directory/v1/users?maxResults=100&alt=json 
returned "Bad Request">

因此,我很确定请求已到达API。我不清楚为什么会拒绝访问。

解决方法

根据评论将其发布为Community Wiki。

要解决此问题,尽管开发人员仍在对其进行调查/检查-此Github问题https://forms.office.com/Pages/ResponsePage.aspx?id=bGOiBG0y_0iT-HCYdb06qZZ8CdlEQAhOkRllU1E9dVZUMVk1VTZFWThQV1FQUTFUV0FKNkNOVldMSi4u中的更多信息-您需要将您的服务帐户添加到更多角色,才能访问G来自App Engine Python的Suite Directory API。您将需要以超级管理员身份开始发送主题,因此您不再面临权限问题。这是基于链接问题的评论。