通过服务帐户访问 Google 管理员 API

Accessing Google Admin API via Service Account

是否可以通过服务器到服务器服务帐户授权访问 Google 管理报告 API?

我尝试按照教程 here.

对 Google 管理员 API 进行服务器到服务器调用

设置全域委派时,我添加了这些范围:https://www.googleapis.com/auth/admin.reports.usage.readonly, https://www.googleapis.com/auth/admin.reports.audit.readonly,定义为 here

我尝试使用相关的 PyPI 包进行 API 调用:

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 401 when requesting https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/login?maxResults=10&alt=json returned "Access denied. You are not authorized to read activity records.". Details: "[{'message': 'Access denied. You are not authorized to read activity records.', 'domain': 'global', 'reason': 'authError', 'location': 'Authorization', 'locationType': 'header'}]">

当我使用不同的凭据方法(例如桌面应用程序)进行 API 调用时,调用按预期进行。但是,我第一次 运行 它时,我必须通过浏览器与它交互才能 approve/authenticate 调用。因为此代码将 运行 宁在服务器上而无需用户交互,这是不可取的行为。

请注意,docs for the Admin API

Your application must use OAuth 2.0 to authorize requests. No other authorization protocols are supported.

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

在 Google Workspace 域中,域管理员可以授予第三方应用程序在域范围内访问其用户数据的权限——这称为域范围授权。 Perform Google Workspace Domain-Wide Delegation of Authority

文档甚至有一个 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.表示您没有为用户正确设置委派。联系您的工作区管理员,让他们调查一下。