如何使用刷新令牌为Google SpreadsheetsService获取新的访问令牌?
本文关键字:获取 访问令牌 SpreadsheetsService Google 何使用 刷新 令牌 | 更新日期: 2023-09-27 18:14:02
我试图建立一个应用程序,读取和写入一个私人谷歌电子表格。为此,我需要使用Google OAuth2.0。
我的问题是,我失去访问1小时后。我认为这意味着刷新令牌没有被正确使用。下面是我处理身份验证的代码:
public static SpreadsheetsService AuthenticateOauth(string clientId, string clientSecret, string userName)
{
string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents
DriveService.Scope.DriveAppdata,
DriveService.Scope.DriveAppsReadonly,
DriveService.Scope.DriveFile,
DriveService.Scope.DriveMetadataReadonly,
DriveService.Scope.DriveReadonly,
"https://spreadsheets.google.com/feeds",
"https://docs.google.com/feeds"
};
try
{
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("MY.APP.Auth.Store")).Result;
SpreadsheetsService service = new SpreadsheetsService(My App");
var requestFactory = new GDataRequestFactory("My App");
requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
service.RequestFactory = requestFactory;
return service;
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString("HH:mm") + ": An authentication error occurred: " + ex.InnerException);
return null;
}
}
如何使刷新令牌被正确使用?
您正在使用当前的Google . net客户端库进行身份验证。当您创建服务时,它通常会在需要时自动刷新您的访问令牌。但是,您正在向旧的Gdata库发送访问令牌,这不会自动刷新它。
如果您创建一个驱动器服务并每小时对它运行一次虚拟请求,它将在需要时为您刷新访问令牌。
var service = new DriveService(new BaseClientService.Initializer() {HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",});
// Dummy request example:
FilesResource.ListRequest list = service.Files.List();
list.MaxResults = 1;
list.Q = "title=dummysearch";
FileList dummyFeed = list.Execute();
// End of Dummy request