服务帐户 - Google 驱动器的全域授权失败

Service account - domain-wide authority failing for Google Drive

我正在尝试设置服务帐户和全域权限。我已成功创建服务帐户并授予全域权限。

我已经为服务帐户启用了所有必需的范围:

在代码中,我可以使用我们域用户的日历或邮件,但不能使用驱动器。

我运行以下代码:

public static readonly string[] REQUIRED_PERMISSIONS =
{
   CalendarService.Scope.Calendar,
   "https://www.google.com/m8/feeds/contacts",
   TasksService.Scope.Tasks,
   DriveService.Scope.Drive,
   DriveService.Scope.DriveAppsReadonly,
   DriveService.Scope.DriveFile,
   DriveService.Scope.DriveAppdata,
   DriveService.Scope.DriveMetadataReadonly,
   DriveService.Scope.DriveReadonly,
   GmailService.Scope.MailGoogleCom
};

var cred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("user.iam.gserviceaccount.com")
{
    Scopes = REQUIRED_PERMISSIONS,
    User = "test@domain"
}.FromPrivateKey(@"privatekey"));

var mailService = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = cred,
    ApplicationName = ApplicationName,
});

var result = mailService.Users.GetProfile("me");

var resultFetch = result.Execute();

我收到错误 Google.Apis.Auth.OAuth2.Responses.TokenResponseException: 'Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.", Uri:""'

我知道我正在使用 GMail 请求,但这只是为了 "test connection" 稍后将使用驱动器请求

当我删除与驱动器相关的范围时,一切正常 - 但这不是解决方案。

我有:

  1. 开启全域权限
  2. 我已创建服务帐户
  3. 我启用了驱动器 API

我也试过这些问题: Access Domain wide Google Drive data with ServiceAccount Actor user

您的问题是由于您使用了太多 scopes 并且它们重叠了它们的权限。我的意思是 DriveService.Scope.Drive 将允许您执行任何操作(读取/ create/write/删除),而 DriveService.Scope.DriveAppsReadonly 将只允许您执行读取操作(get/list) ,因此它会剥夺您事先设置的权限。

我建议您仅使用 DriveService.Scope.Drive 范围进行测试,然后根据需要限制更多权限。另外,不要忘记更改管理 API 客户端访问中的范围。

您可以检查所有驱动器 API 作用域 HERE