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

我已验证我的服务:

String serviceAccountEmail = "[email protected]";

var certificate = new X509Certificate2(@"privatekey.p12", "pass", X509KeyStorageFlags.Exportable);

ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        Scopes = new[] { DriveService.Scope.Drive }
    }.FromCertificate(certificate));

从这里我可以实例化几乎所有服务。

例如驱动器服务:
var service = new DriveService(new BaseClientService.Initializer()
    {
            HttpClientInitializer = credential,
            ApplicationName = "Drive API Sample",
    });

但是我可以使用SpreadsheetsService做到这一点,因为SpreadsheetsService等待其默认构造函数中的字符串“应用程序名称”或其属性RequestFactory中的GOAuth2RequestFactory。

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

最佳答案

这是如何执行此操作的答案.....
关键是在新的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;

10-07 20:15