Login Required 401 using Google ServiceAccountCredential using Google Admin Directory API

前端 未结 2 1344
孤城傲影
孤城傲影 2021-01-23 15:42

I have tried to follow the simple example listed here: https://developers.google.com/admin-sdk/directory/v1/quickstart/dotnet

The difference is I generated a Service Acc

2条回答
  •  一向
    一向 (楼主)
    2021-01-23 16:09

    This has been answered but adding more details here. If anyone wants to impersonate user to upload file on google drive using Service account. Follow these steps

    • Create Service Account
    • Enable Site Wide delegation for service account
    • Get Service account client ID
    • Enable Client ID to use Google Drive API using Google Admin Console->Manage API
    • Use the below C# code to upload file

      public static DriveService GetService()
      {
          string[] scopes = new string[] { DriveService.Scope.Drive };
      
      
         //"SERVICE_ACCOUNT_EMAIL_HERE";
          String serviceAccountEmail = "test-417@elated-graph-261115.iam.gserviceaccount.com";
      
          // Scope and user email id which you want to impersonate
          var initializer = new ServiceAccountCredential.Initializer(serviceAccountEmail)
          {
              Scopes = scopes,
              User = "yourEmail@domain.com"
          };
      
          //get private key, from .JSON file
          var credential = new ServiceAccountCredential(initializer.FromPrivateKey("-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCkHeAicu6uFQn0\n7KUVTjgZ68nQui8+c8NmKW8aW8vhkBIKfdewXFECiUlTMPyI+HXbubsCK5Dl2xBS\nnphLq6YyE0xEQxNFLYHwfUKuzGQ2rV+qObcZ0mLZjCaf+pw3YiRVuU6OtslLJKJH\n-----END PRIVATE KEY-----\n"));
      
      
          // Create the service.
          var service = new DriveService(new BaseClientService.Initializer()
          {
              HttpClientInitializer = credential,
              ApplicationName = "DriveAPI",
          });
      
      
      
      
          service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
          return service;
      }
      

    That's it, we are done above Code is using Impersonation/Delegation for uploading file on Google Drive using Service account

    Reference : Upload file to Google Drive using Service Account in C# MVC (With Impersonation)

提交回复
热议问题