我的会话每小时到期,当我使用服务帐户身份验证方法时,我找不到有关如何刷新令牌的文档。对于已安装的应用程序,我可以从RefreshToken
对象
state
AuthorizationState state = new AuthorizationState(new[]
{
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.metadata.readonly",
"https://www.googleapis.com/auth/drive.readonly"
})
{
Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl)
}
state = client.ProcessUserAuthorization(GetAuthorizationCode(), state);
Console.WriteLine(state.RefreshToken);
但如何为服务帐户执行此操作?
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "mysecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DriveService.Scopes.Drive.GetStringValue(),
ServiceAccountUser = "myemail@mydomain.com",
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
DriveService service = DriveService(auth);
来自Google SDK源代码我发现AssertionFlowClient.GetState
函数执行以下操作
IAuthorizationState state = new AuthorizationState(provider.Scope.Split(' '));
if (provider.RefreshToken(state, null)) {
return state;
} else {
return null;
}
看起来像令牌刷新。我将此函数调用添加到我的令牌刷新计时器,但它没有帮助。一小时后我仍然会继续Invalid credentials
例外。
答案 0 :(得分:0)
服务帐户不使用刷新令牌。您只需使用第一次使用的相同过程请求另一个访问令牌。请参阅Google有关如何执行when access tokens expire的文档。