如何使用ServiceAccountCredential认证的SpreadsheetsService?

Eri*_*tas 6 .net google-api google-authentication google-sheets google-spreadsheet-api

我需要使用SpreadsheetsService,但我没有在官方文档中找到方法.net. https://developers.google.com/google-apps/spreadsheets/?hl=ja#authorizing_requests

我的服务已通过身份验证:

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));
Run Code Online (Sandbox Code Playgroud)

从这里我可以实例化几乎任何服务.

例如Drive Service:

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

但是SpreadsheetsService我可以这样做,因为SpreadsheetsService在他的默认构造函数或其属性中的GOAuth2RequestFactory中等待字符串'application name' RequestFactory.

如何使用ServiceAccountCredential对SpreadsheetsService进行身份验证?

小智 5

以下是如何执行此操作的答案.....关键是在新的requestFactory上使用customHeaders

 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;
Run Code Online (Sandbox Code Playgroud)