我大约每 1.5 分钟用我的 C# 应用程序执行一次 Google 应用程序脚本。应用程序脚本在电子表格之间移动内容,并编辑工作表。我也使用 Drive API。
我的脚本在很长一段时间内运行良好,除了我每小时收到 5 分钟的授权错误。
这是我处理授权的代码:
class Authentication
{
public static ScriptService ScriptsAuthenticateOauth(UserCredential credential)
{
try
{
ScriptService service = new ScriptService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString("HH:mm") + ": An authentication error occurred: " + ex.InnerException);
return null;
}
}
public static UserCredential getCredential(string clientId, string clientSecret, string userName)
{
string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents
DriveService.Scope.DriveAppdata, // view and manage its own configuration data
DriveService.Scope.DriveAppsReadonly, // view your drive apps
DriveService.Scope.DriveFile, // view and manage files created by this app
DriveService.Scope.DriveMetadataReadonly, // view metadata for files
DriveService.Scope.DriveReadonly, // view files and documents on your drive
DriveService.Scope.DriveScripts, // modify your app scripts
ScriptService.Scope.Drive,
"https://www.googleapis.com/auth/spreadsheets",
"https://spreadsheets.google.com/feeds",
"https://docs.google.com/feeds"};
return GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("Google.Sheet.Sync.Auth.Store")).Result;
}
public static DriveService DriveAuthenticateOauth(UserCredential credential)
{
try
{
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
// Console.WriteLine("Auth success");
return service;
}
catch (Exception ex)
{
// Console.WriteLine(ex.InnerException);
Console.WriteLine(DateTime.Now.ToString("HH:mm") + ": An authentication error occurred: " + ex.InnerException);
return null;
}
}
}
我得到这样的服务:
var credential = Authentication.getCredential(CLIENT_ID, CLIENT_SECRET, Environment.UserName);
DriveService driveService = Authentication.DriveAuthenticateOauth(credential);
ScriptService scriptService = Authentication.ScriptsAuthenticateOauth(credential);
但是大约在一个小时结束时,应用程序脚本调用会引发以下错误:
Script error message: Authorization is required to perform that action.
需要明确的是,它在所有其他时间都有效,只是在接近一小时结束的那 5 分钟内无效。我确实在我的开发人员控制台上以及在应用程序脚本编辑器中的 Resources > Advanced Google services... 下激活了 Google Drive API。
那么发生了什么?这可以解决吗?