通过服务帐户访问Google Admin API



是否可以通过服务器到服务器的服务帐户授权访问Google Admin Reports API?

我正在尝试对谷歌管理员API进行服务器到服务器的调用,遵循这里的教程。

在设置域范围委派时,我添加了以下作用域:https://www.googleapis.com/auth/admin.reports.usage.readonly, https://www.googleapis.com/auth/admin.reports.audit.readonly,如这里所定义的。

我试着这样调用API,使用相关的PyPI包:

creds = service_account.Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
with build('admin', 'reports_v1', credentials=creds) as service:
response = service.activities().list(userKey='all', applicationName='login', maxResults=10).execute()

这导致以下错误:

googleapiclient.errors.HttpError:<请求时出现HttpError 401https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/login?maxResults=10&alt=json返回";访问被拒绝。您无权读取活动记录&";。详细信息:;[{'message':'访问被拒绝。您无权读取活动记录。','domain':'global','reason':'authError','location':'Authorization','locationType':'header'}]"gt;

当我使用不同的凭据方法(如桌面应用程序(进行API调用时,该调用将按预期工作。然而,当我第一次运行它时,我必须通过浏览器与它交互,以批准/验证呼叫。因为此代码将在没有用户交互的情况下在服务器上运行,所以这不是理想的行为。

注意,管理员API的文档显示

您的应用程序必须使用OAuth 2.0来授权请求。不支持其他授权协议。

根据服务器到服务器调用的文档,我认为服务帐户仍然符合OAuth 2.0的条件,但我的假设可能是错误的。

在Google Workspace域中,域管理员可以授予第三方应用程序对其用户数据的全域访问权限,这被称为全域授权。执行谷歌工作区域授权

文档中甚至有一个python示例。

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
"""Email of the Service Account"""
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'
"""Path to the Service Account's Private Key file"""
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'
def create_reports_service(user_email):
"""Build and returns an Admin SDK Reports service object authorized with the service accounts
that act on behalf of the given user.
Args:
user_email: The email of the user. Needs permissions to access the Admin APIs.
Returns:
Admin SDK reports service object.
"""
credentials = ServiceAccountCredentials.from_p12_keyfile(
SERVICE_ACCOUNT_EMAIL,
SERVICE_ACCOUNT_PKCS12_FILE_PATH,
'notasecret',
scopes=['https://www.googleapis.com/auth/admin.reports.audit.readonly'])
credentials = credentials.create_delegated(user_email)
return build('admin', 'reports_v1', http=http)

请注意,user_email是您代表的用户,而不是服务帐户电子邮件。

错误消息Access denied. You are not authorized to read activity records.表示您没有为用户正确设置委派。联系你的工作区管理员,让他们调查一下。

最新更新