googleapis / google-api-dotnet-client

Google APIs Client Library for .NET
https://developers.google.com/api-client-library/dotnet
Apache License 2.0
1.36k stars 528 forks source link

Token not refreshing automatically ? #2827

Closed nir-tsabari closed 2 months ago

nir-tsabari commented 2 months ago

Hey there, I'm having an issue with the Google API Client. I'm using the UserCredential class, which is supposed(?) to automatically refresh the access token when it's about to expire or when stale. However, I'm getting a "refresh token error" after about an hour, which is when the access token expires.

Here's my code:

var service = new GmailService(
    new BaseClientService.Initializer
    {
        HttpClientInitializer = credential,
        ApplicationName = "ApplicationName"
    }
);

if (credential.Token.IsStale) // Added after I had refresh token errors
    await credential.RefreshTokenAsync(CancellationToken.None);

I'm expecting the UserCredential to automatically refresh the token, but instead, I'm getting an error. I've made sure to use the same credential object (referential equality) and I'm making slow, sequential requests, so it's not a concurrency issue.

Can anyone help me figure out what's going on? Are my expectations wrongly set of the GmailService and it's interaction with the UserCredentials ?

jskeet commented 2 months ago

Could you provide a minimal but complete example, and ideally a full stack trace rather than just part of a message? Additionally, you say you've added code to automatically refresh the token (but only when creating the service?) but we don't know what impact that had.

One thing that can affect refresh is clock skew - please check that your system clock is correct. (I'd expect it to be, but it's worth checking.)

amanda-tarafa commented 2 months ago

UserCredential does refresh the access token automatically if it knows of a refresh token, which it does by default, for instance, if you obtained the credential using Google.Apis.Auth.OAuth.GoogleWebAuthorizationBroker.

If you provide a minimal but complete console application that reproduces the issue we can look into it.

amanda-tarafa commented 2 months ago

@nir-tsabari I'll close this issue as we cannot help you furhter if we cannot reproduce. Do leave a new comment if you can share a repro and we'll look into it.