How to use authenticated spreadsheet tables through ServiceAccountCredential?

I need to use SpreadsheetsService, but I did not find a way in the official .net documentation. https://developers.google.com/google-apps/spreadsheets/?hl=ja#authorizing_requests

I have authentication of my service:

 String serviceAccountEmail = " serviceAccount@developer.gserviceaccount.com "; var certificate = new X509Certificate2(@"privatekey.p12", "pass", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { DriveService.Scope.Drive } }.FromCertificate(certificate)); 

From here I can create almost any service.

For example, the disk service:

 var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Drive API Sample", }); 

But with SpreadsheetsService I can do this because SpreadsheetsService is waiting for the string "application name" in its default constructor or GOAuth2RequestFactory in its RequestFactory property.

How to authenticate service tables using ServiceAccountCredential?

+6
source share
2 answers

Here is the answer on how to do this ..... The key is to use customHeaders on the new requestFactory

  var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(p12KeyFileName, "notasecret", X509KeyStorageFlags.Exportable); string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds"; Google.Apis.Auth.OAuth2.ServiceAccountCredential credential = new Google.Apis.Auth.OAuth2.ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { SCOPE } }.FromCertificate(certificate)); bool success = credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result; var requestFactory = new Google.GData.Client.GDataRequestFactory("My Plastic SCM Service"); requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken)); var s = new SpreadsheetsService("MySpreadsheetIntegration-v1"); s.RequestFactory = requestFactory; return s; 
+5
source

Please note that when adding a custom header you need: "Authorization: carrier {0}" <- with a space between the "carrier" and "{0}" Because: "Authorization: carrier {0}" - there is no place you will only get "unknown authorization header" Error 401 response

0
source

Source: https://habr.com/ru/post/970747/


All Articles