gpt4 book ai didi

.net - 如何使用由 ServiceAccountCredential 认证的 SpreadsheetsService?

转载 作者:行者123 更新时间:2023-12-04 15:11:06 25 4
gpt4 key购买 nike

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

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

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

但与 SpreadsheetsService我可以这样做,因为 SpreadsheetsService 在其默认构造函数中等待字符串“应用程序名称”或在其属性中等待 GOAuth2RequestFactory RequestFactory .

如何使用 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;

关于.net - 如何使用由 ServiceAccountCredential 认证的 SpreadsheetsService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24185206/

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