2
votes

My session expires every hour and I can't find documentation on how to refresh token when I'm using service accounts authentication method. For installed applications I'm able to get RefreshToken from state object

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);

but how to do that for service accounts?

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 = "[email protected]",
};

var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
DriveService service = DriveService(auth);

from Google SDK source codes I found that AssertionFlowClient.GetState function performs the following

    IAuthorizationState state = new AuthorizationState(provider.Scope.Split(' '));

    if (provider.RefreshToken(state, null)) {
        return state;
    } else {
        return null;
    }

So looks like it does token refresh. I added this function call to my token refresh timer, but it doesn't help. I still continue to get Invalid credentials exception after one hour.

1
could you please little more clarify your requiremen? What i understand from above is that, you have refresh token and all you want is new access token, am i right ? - Ramesh Karna

1 Answers

0
votes

Service accounts do not use refresh tokens. You simply need to request another access token using the same procedure you used the first time. See Google's documentation on what to do when access tokens expire.