C# 使用Google Drive API中的服务帐户下载文件时出现未经授权的响应

C# 使用Google Drive API中的服务帐户下载文件时出现未经授权的响应,c#,.net,google-oauth,google-api-dotnet-client,google-drive-api,C#,.net,Google Oauth,Google Api Dotnet Client,Google Drive Api,我使用以下代码从Google的身份验证服务器获取凭证,以便访问Google drive API public static Google.Apis.Services.BaseClientService.Initializer getCredentials() { String serviceAccountEmail = "xxx@developer.gserviceaccount.com"; var certificate = new X509Cer

我使用以下代码从Google的身份验证服务器获取
凭证
,以便访问
Google drive API

 public static Google.Apis.Services.BaseClientService.Initializer getCredentials()
    {

        String serviceAccountEmail = "xxx@developer.gserviceaccount.com";

        var certificate = new X509Certificate2(@"xxx.p12", "notasecret", X509KeyStorageFlags.Exportable);

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



        return new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "AppName",
        };



    }
然后从文件元数据检索下载url,并尝试使用以下代码下载该文件:

 public static System.IO.Stream DownloadFile(Google.Apis.Drive.v2.Data.File file, Google.Apis.Drive.v2.DriveService service)
   {



       if (!String.IsNullOrEmpty(file.DownloadUrl))
       {
           try
           {
               HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                   new Uri(file.DownloadUrl));
              // authenticator.ApplyAuthenticationToRequest(request);
               HttpWebResponse response = (HttpWebResponse)request.GetResponse();
               if (response.StatusCode == HttpStatusCode.OK)
               {
                   return response.GetResponseStream();
               }
               else
               {
                   Console.WriteLine(
                       "An error occurred: " + response.StatusDescription);
                   return null;
               }
           }
           catch (Exception e)
           {
               Console.WriteLine("An error occurred: " + e.Message);
               return null;
           }
       }
       else
       {
           // The file doesn't have any content stored on Drive.
           return null;
       }
   }

但是我收到了一个
401未经授权的
响应。我假设我需要在请求中添加一个授权头,其授权行如下:
Bearer{ACCESS\u TOKEN}
但是
HttpClientInitializer.TOKEN
属性为空。是否可以使用
ServiceAccountCredential
验证此请求?

您的代码有点不正确。我现在还没有谷歌驱动API示例的服务帐户。这是一个大问题,几乎是一样的

String serviceAccountEmail = "539621478854-imkdv94bgujcom228h3ea33kmkoefhil@developer.gserviceaccount.com";
var certificate = new X509Certificate2(@"C:\Users\linda_l\Documents\GitHub\GoogleBigQueryServiceAccount\GoogleBigQueryServiceAccount\key.p12", "notasecret", X509KeyStorageFlags.Exportable);

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

        // Create the service.
var service = new BigqueryService(new BaseClientService.Initializer()
      {
       HttpClientInitializer = credential,
       ApplicationName = "BigQuery API Sample",
       });
您可以看到在哪里使用
BaseClientService.Initializer()
来创建
BigqueryService
。我认为您需要创建一个
GoogleDriveService
。创建服务后,您应该能够使用该服务下载文件。您不需要通过HTTPRequest执行此操作


我会看看今晚是否能用谷歌硬盘找到更好的例子。

我今天也遇到了同样的问题。使用您的方法发出请求时,不提供身份验证标头。我需要以稍微不同的方式构造请求。如果您有:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
               new Uri(file.DownloadUrl));
你应该:

HttpResponseMessage response = await service.HttpClient.GetAsync(new Uri(file.DownloadUrl));

这可以确保请求得到正确的身份验证。

Perfect。我能够使用service.HttpClient.GetByteArrayAsync(新Uri(file.DownloadUrl))来做我想做的事情。