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

使用service account调用Google Admin API报403无权限错误如何解决?

核心原因

Google Admin Directory API不支持服务账号直接调用,必须配置全域委派权限后,模拟一个域内拥有目录管理权限的用户身份才能发起请求,这是API的强制要求,和你给服务账号单独配的资源权限无关。

修复步骤
  • 先找域管理员确认两项配置正确:
    • 对应服务账号已在Google Cloud控制台开启「全域委派访问」开关
    • 域管理员已在Google Admin后台的API权限管理页,给该服务账号的客户端ID授权了如下完整Scope:
      https://www.googleapis.com/auth/admin.directory.user
      https://www.googleapis.com/auth/admin.directory.user.readonly
  • 修改你的C#代码,在凭证初始化时指定模拟的管理员用户邮箱,修改后的核心代码如下:
static void Main(string[] args)
{
    try
    { 
        // Create a ServiceAccountCredential credential
        var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("saxxxxxxxx@directorysync-xxxxxx.iam.gserviceaccount.com")
        {
            // 新增该行,替换为你们域内拥有用户管理权限的管理员真实邮箱
            User = "admin@mycompany.com",
            Scopes = new[] {
                    DirectoryService.Scope.AdminDirectoryUser,
                    DirectoryService.Scope.AdminDirectoryUserReadonly
                }
        }.FromPrivateKey("-----BEGIN PRIVATE KEY-----\nMI...p9XnI4DZFO/QQJc=\n-----END PRIVATE KEY-----\n"));

        // Create the service
        DirectoryService service = new DirectoryService(
            new BaseClientService.Initializer()
            {
                HttpClientInitializer = xCred,
            }
        );
        
        var listReq = service.Users.List();
        listReq.Domain = "mycompany.com";
        listReq.MaxResults = 100;
        listReq.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;
        Users results = listReq.Execute();
        //  process the users list here...
        
    }
    catch (Exception e)
      { Console.WriteLine(e.Message); }
}
其他排查项
  • 确认代码中listReq.Domain填写的是你司Google Workspace绑定的主域名,不要填写域名别名
  • 若使用JSON密钥文件导入凭证,可使用更简便的加载方式,避免手动复制密钥出错:
var xCred = GoogleCredential.FromFile("你的服务账号密钥文件路径.json")
    .CreateScoped(new[] {
        DirectoryService.Scope.AdminDirectoryUser,
        DirectoryService.Scope.AdminDirectoryUserReadonly
    })
    .CreateWithUser("admin@mycompany.com")
    .UnderlyingCredential as ServiceAccountCredential;
  • 确认你模拟的用户账号本身确实在Google Admin后台拥有用户管理权限,没有被权限限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:09:06