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的谷歌應用程序中。

相關問題