在Google Drive API中使用服务帐户下载文件时,未经授权的响应

本文关键字:文件 响应 授权 下载 API Drive Google 服务 | 更新日期: 2023-09-27 18:05:45

我使用以下代码从Google的身份验证服务器获取credentials,以便访问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 unauthorized响应。我假设我需要在请求中添加一个授权头,沿着Authorization: Bearer {ACCESS_TOKEN}的行,但HttpClientInitializer.Token属性为空。是否可以使用ServiceAccountCredential验证此请求?

在Google Drive API中使用服务帐户下载文件时,未经授权的响应

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

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
               new Uri(file.DownloadUrl));

你应该有:

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

您的代码有点偏离。我没有一个服务帐户谷歌驱动器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来执行此操作。

我看看今晚能否找到一个更好的使用Google Drive的例子。