如何使用ServiceAccountCredential认证的SpreadsheetsService?

时间:2014-06-12 13:06:01

标签: .net google-api google-sheets google-spreadsheet-api google-authentication

我需要使用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));

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

例如Drive Service:

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

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

如何使用ServiceAccountCredential验证SpreadsheetsService?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

请注意,添加自定义标题时,您需要: “授权:承载{0}”< - 在“承载”和“{0}”之间留有空格 因为: “授权:持票人{0}”< - 没有空格 只会得到一个“未知的授权标题”错误401响应