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

Python Web应用调用Google Admin SDK Directory API获取域用户信息时遭遇400 Bad Request错误排查求助

解决Google Admin SDK Directory API调用时的400 Bad Request错误

根据你描述的场景和代码,这个400错误大概率是参数配置或服务账户授权环节出了问题,我来拆解下可能的原因和对应的解决办法:

1. customer 参数使用错误

Admin SDK的users.list接口里,customer参数要求传入的是Google Workspace的客户唯一ID(通常是一个以C开头的字符串,比如C123abc),而不是域名customer.com。同时你已经指定了domain参数来筛选域内用户,同时传递这两个参数会触发API的参数校验冲突,直接返回Bad Request。

解决办法:

  • 如果不需要按客户ID筛选,直接移除customer='customer.com'这个参数,只保留domain参数即可;
  • 如果确实需要使用客户ID,先从Google Workspace管理控制台获取正确的ID(路径:Admin Console > 账号 > 账号设置 > 个人资料 > 客户ID),再替换到参数中。

2. 服务账户未完成域范围授权(Domain-Wide Delegation)

虽然你已经给服务账户授权了admin.directory.user.readonly权限,但服务账户本身无法直接访问Google Workspace域内的用户数据,必须完成域范围授权,让它能代表域内的某个管理员用户发起API请求。

解决办法:

  1. 登录客户的Google Workspace管理控制台,进入「安全 > API 控件 > 全域委派」;
  2. 添加你的服务账户的客户端ID(可以从服务账户JSON凭据的client_id字段获取),并授予https://www.googleapis.com/auth/admin.directory.user.readonly权限范围;
  3. 在代码中创建凭据时,通过subject参数指定一个域内的管理员邮箱(比如admin@customer.com),让服务账户以该用户身份发起请求。

修正后的代码示例

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

credential_path = os.path.join(os.path.dirname(app.instance_path), 'cre.json')
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']

# 获取凭据并指定要委派的域管理员邮箱
credentials = service_account.Credentials.from_service_account_file(
    credential_path,
    scopes=SCOPES,
    subject='admin@customer.com'  # 替换为客户域的管理员邮箱
)

service = build('admin', 'directory_v1', credentials=credentials)

# 移除错误的customer参数,仅保留domain参数
print('Getting the first 10 users in the domain')
results = service.users().list(domain='customer.com', maxResults=10, orderBy='email').execute()
users = results.get('users', [])

for user in users:
    print(u'{0} ({1})'.format(user['primaryEmail'], user['name']['fullName']))

额外检查点

  • 确认服务账户JSON凭据的路径正确,没有拼写错误;
  • 确认客户的Google Workspace订阅包含Admin SDK的访问权限(部分基础版可能限制API访问)。

内容的提问来源于stack exchange,提问作者Gustavo Castanheira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:37:49