[我们使用Python从特定的G Suite托管域中获取所有用户,但是在完成以下tutorial并授予了服务帐户所需的所有访问权限之后,以下代码段仍会产生“未授权访问此资源/ api :
import json
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES)
service = build('admin', 'directory_v1', credentials=credentials)
Google documentation中有一个(非常模糊的)解决方案线索:
注意:只有具有Admin API访问权限的用户才能访问AdminSDK Directory API,因此您的服务帐户需要模拟这些用户之一访问Admin SDK Directory API。此外,用户必须至少登录一次并接受G Suite服务条款。
在Python中实现模拟的方法是,在通过OAuth2库进行身份验证时发送“主题”。主题应该是有权访问Admin API的用户(他不必是管理员,用户管理角色应该足够,至少满足我的需要)。
一个有效的代码段:
import json
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES, subject="[email protected]")