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

使用C#调用Google API获取用户列表返回badRequest错误求助

问题诊断与解决方案

核心问题

  1. 服务账号缺少域范围委派模拟:Workspace服务账号调用Directory API必须模拟域内管理员账号,你的代码注释掉了CreateWithUser(googleAdminEmail),这是关键缺失步骤。
  2. 参数冲突+取值错误:Customer参数不能填域名,且同时设置Customer和Domain会导致请求冲突。

具体修复步骤

1. 启用域范围委派并模拟管理员账号

服务账号本身没有Workspace域的访问权限,必须通过模拟域内管理员账号获取权限:

  • 取消代码中CreateWithUser的注释,确保传入的googleAdminEmail是Workspace域的管理员邮箱(比如admin@test.example.com)。
  • 提前在Google Cloud控制台给该服务账号配置域范围委派,并在Workspace Admin控制台的API权限页面,授权DirectoryService.Scope.AdminDirectoryUser权限。

修改后的凭证初始化代码:

GoogleCredential credential = GoogleCredential.FromFile(googleTokenPath)
    .CreateScoped(googleScopes)
    .CreateWithUser(googleAdminEmail);

2. 修正Users.List的参数设置

Customer和Domain参数二选一即可,不要同时设置:

  • 选Domain:直接填你的域名test.example.com,删掉request.Customer的设置。
  • 选Customer:填Workspace的Customer ID(格式为Cxxxxxx,可在Workspace Admin控制台「账号」>「账号设置」中找到),或者用my_customer(仅当模拟的是域管理员时有效),删掉request.Domain的设置。

示例(使用Domain参数):

var request = service.Users.List();
request.Domain = "test.example.com";
// 移除 request.Customer = "test.example.com";
var result = await request.ExecuteAsync();

3. 验证权限配置

  • 确认服务账号已在Workspace Admin控制台被授予Directory Service > Users > Read权限。
  • 确认模拟的管理员账号本身拥有查看域内用户的权限。

额外排查点

  • 检查Google Cloud控制台中,Directory API是否已启用(在「API与服务」>「已启用的API与服务」中确认)。
  • 确保程序能正常读取服务账号的JSON凭证文件,文件权限无问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:02:46