0

我想上传文件到谷歌驱动器。为此,我有一个启用了域范围权限的服务帐户。 “@xyx.com”是我的域名。我有一个共同的“[email protected]”谷歌驱动器。模仿用户电子邮件到谷歌服务帐户

Google服务帐号为“[email protected]”。我需要将文件上传到“[email protected]”。我试图模仿服务帐户的“[email protected]”。

下面是我的代码

public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) 
 
     { 
 
      // check the file exists 
 
      if (!File.Exists(keyFilePath)) 
 
      { 
 
       return null; 
 
      } 
 

 
      //Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes 
 
      string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents 
 
              DriveService.Scope.DriveAppdata, // view and manage its own configuration data 
 
              DriveService.Scope.DriveFile, // view and manage files created by this app 
 
              DriveService.Scope.DriveMetadata, 
 
              DriveService.Scope.DriveMetadataReadonly, // view metadata for files 
 
              DriveService.Scope.DrivePhotosReadonly, 
 
              DriveService.Scope.DriveReadonly, // view files and documents on your drive 
 
              DriveService.Scope.DriveScripts }; // modify your app scripts  
 

 

 
      var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); 
 
      try 
 
      { 
 
       ServiceAccountCredential credential = new ServiceAccountCredential(
 
        new ServiceAccountCredential.Initializer(serviceAccountEmail) 
 
        { 
 
         Scopes = scopes, 
 
         User = "[email protected]", 
 
        }.FromCertificate(certificate)); 
 
       DriveService service = new DriveService(new BaseClientService.Initializer() 
 
       { 
 
        HttpClientInitializer = credential, 
 
        ApplicationName = "CIM_GD_UPLOAD", 
 
       }); 
 
       return service; 
 
      } 
 
      catch (Exception ex) 
 
      { 
 
       throw ex; 
 
      } 
 
     }

我收到以下错误。

Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method.", Uri:"" 

我使用谷歌API V3

请帮助我,是否可以模拟用户帐户到服务帐户?或引导我正确的方式上传/从谷歌驱动器检索文件。

回答

0

参考Google Drive API Authorization,您需要授权使用OAuth 2.0的请求才能访问Google API。授权流程的第一步是从Google API Console获取OAuth 2.0凭据。当您使用服务帐户时,同样的过程会发生,您必须生成服务帐户凭证,然后delegate domain-wide authority to the service account

你可能想尝试在陈述这个documentation

如果你已经委派域范围内的访问服务帐户,你要模拟用户帐户,指定用户帐户的电子邮件地址用GoogleCredential工厂的setServiceAccountUser方法。例如:

GoogleCredential credential = new GoogleCredential.Builder() 
    .setTransport(httpTransport) 
    .setJsonFactory(JSON_FACTORY) 
    .setServiceAccountId(emailAddress) 
    .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12")) 
    .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)) 
    .setServiceAccountUser("[email protected]") 
    .build(); 

使用GoogleCredential对象调用API的谷歌应用程序中。

相关问题