You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Admin SDK Reports API服务账号调用遇HttpError 401“Access denied”问题求助

Google Admin SDK Reports API服务账号调用遇HttpError 401“Access denied”问题求助

Hey,我之前踩过这个坑!看你的描述和代码,问题大概率出在服务账号没有模拟域内的授权用户——服务账号本身没有Google Workspace域内的权限,哪怕开了域宽委派,也必须指定一个拥有对应权限的域内用户来模拟才行。

咱们来逐个解决你的问题:

1. 所需的具体角色/权限

你需要给要模拟的域内用户分配 Reports Viewer 角色(遵循最小权限原则,不用直接给超级管理员权限)。这个角色专门用来读取Google Workspace的审计报告数据,完全匹配你要调用的Reports API的需求。

2. 是否需要额外的管理员权限?

不需要给服务账号本身分配Admin控制台的权限,而是要确保两点:

  • 你用来模拟的域内用户已经拥有上述的Reports Viewer(或更高权限,比如超级管理员)角色
  • 服务账号的域宽委派配置完全正确:客户端ID已添加到Admin Console,且指定的admin.reports.audit.readonly scope没有拼写错误

修复后的代码示例

你需要在创建Credentials的时候加上subject参数,指定要模拟的域内授权用户邮箱:

from google.oauth2 import service_account
from googleapiclient.discovery import build

service_account_file = "path/to/service_account.json"

# 关键:添加subject参数,指定域内有Reports权限的用户邮箱
creds = service_account.Credentials.from_service_account_file(
    service_account_file,
    scopes=['https://www.googleapis.com/auth/admin.reports.audit.readonly'],
    subject='authorized-user@your-domain.com'  # 替换成你的域内用户邮箱
)

service_admin_reports = build(
    'admin', 'reports_v1', credentials=creds
)

results = service_admin_reports.activities().list(
    userKey='all',
    applicationName='admin',
    maxResults=150
).execute()

额外排查点

如果还是报错,可以试试这些:

  • 确认Admin Console里的Reports Viewer角色成员列表里确实包含你指定的模拟用户
  • 暂时用超级管理员邮箱模拟,排除角色权限配置的问题
  • 检查服务账号的JSON密钥文件是否正确,有没有过期或权限变更

备注:内容来源于stack exchange,提问作者code_taco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:18:07