gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:59:14 26 4
gpt4 key购买 nike

我正在使用以下代码从 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 unauthorized 响应。我假设我需要在 Authorization: Bearer {ACCESS_TOKEN} 行的请求中添加授权 header ,但 HttpClientInitializer.Token 属性为空。是否可以使用 ServiceAccountCredential 验证此请求?

最佳答案

我今天遇到了同样的问题。使用您的方法发出请求时未提供身份验证 header 。我需要以不同的方式构建请求。你在哪里:

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

你应该有:

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

这可确保请求得到正确验证。

关于c# - 在 Google Drive API 中使用服务帐户下载文件时出现未经授权的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23944974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com