gpt4 book ai didi

c# - 有没有办法重用 Google.Apis.Auth.OAuth2.UserCredential 对象来授权 SpreadsheetsService?

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:49 25 4
gpt4 key购买 nike

我正在尝试通过 C# 控制台应用程序使用 Google Drive 和 Spreadsheets API。我想使用带有 FileDataStore 的用户凭据对这两项服务进行授权,这样我就不必在每次运行时都重新验证我的应用程序。以下是我如何授权我的云端硬盘服务对象:

var userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync
(
new ClientSecrets
{
ClientId = "[clientID]",
ClientSecret = "[clientSecret]"
},
new []
{
"https://www.googleapis.com/auth/drive",
"https://spreadsheets.google.com/feeds"
},
"[userName]",
CancellationToken.None,
new FileDataStore("MyApp.GoogleDrive.Auth.Store")
).Result;

var driveService = new DriveService
(
new BaseClientService.Initializer
{
HttpClientInitializer = userCredential,
ApplicationName = "MyApp",
}
);

对于电子表格服务,我按照 this guide 的规定进行授权,但每次我运行我的应用程序时,我都必须打开浏览器访问给定的身份验证 URL 并手动复制访问 token 才能使其正常工作。

有没有办法只验证一次,获取上述用户凭据,并将它们用于两种服务?请注意,我正在授权 Drive 和 Spreadsheets 范围,所以我认为这没有问题。

我试图让它像这样工作,但是当我尝试将行插入我的电子表格时,我不断收到 400 Bad Request 错误:

var auth = new OAuth2Parameters 
{
ClientId = "[clientID]",
ClientSecret = "[clientSecret]",
RedirectUri = "[redirectUri]",
Scope = "https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds" ,
AccessToken = userCredential.Token.AccessToken,
RefreshToken = userCredential.Token.RefreshToken,
TokenType = userCredential.Token.TokenType,
};

var requestFactory = new GOAuth2RequestFactory(null, "MyApp", auth);

var spreadsheetsService = new SpreadsheetsService("MyApp")
{
Credentials = new GDataCredentials(userCredential.Token.TokenType + " " + userCredential.Token.AccessToken),
RequestFactory = requestFactory,
};

最佳答案

有没有办法只授权一次,获取上述用户凭据,并将它们用于两种服务?

是的。如果您已包含所有范围并已请求离线访问,那么您将获得一个刷新 token ,您可以存储并重复使用该 token 以根据需要获取访问 token 。显然,您需要考虑安全隐患。

400 错误请求听起来不像是 OAuth 问题。我认为您在这里有两个问题/问题,可能值得开始一个新线程。在您的问题中包含 400 的 http 请求/响应。

关于c# - 有没有办法重用 Google.Apis.Auth.OAuth2.UserCredential 对象来授权 SpreadsheetsService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29839084/

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