question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Authentication problems / is the SDK invalidating my saved access and refresh tokens?

See original GitHub issue

Hi,

I think I’m doing the authentication workflow in the right way, but too ofter I get ‘refresh token has expired’. It is supposed to last for two months, so it can’t be that, because the problem happens within the same day (within hours).

This is what I do: The first time (just once), I get my first access and refresh tokens pair. This is working fine.

Then, in the following hours (and luckily days and so on) I get (and save) new access and refresh tokens doing this:

var config = new BoxConfig(_settings.ClientId, _settings.ClientSecret, new Uri(RedirectUrl));
var sessionInfo = new OAuthSession(_settings.AccessToken, _settings.RefreshToken,
                                                       AccessTokenExpiresSeconds, "bearer");
_client = new BoxClient(config, sessionInfo);

var newSessionInfo = await client.Auth.RefreshAccessTokenAsync(client.Auth.Session.AccessToken);
// and I update _settings.AccessToken and _settings.RefreshToken 
// with the values found in newSessionInfo 

Why then, I’m getting the ‘refresh token has expired’? Digging into the SDK code, I see this in \Box.V2\Managers\BoxResourceManager.cs:

            switch (response.Status)
            {
                // Refresh the access token if the status is "Unauthorized" (HTTP Status Code 401: Unauthorized)
                // This will only be attempted once as refresh tokens are single use
                case ResponseStatus.Unauthorized:
                    response = await RetryExpiredTokenRequest<T>(request).ConfigureAwait(false);
                    break;

...
...
...
        protected async Task<IBoxResponse<T>> RetryExpiredTokenRequest<T>(IBoxRequest request)
            where T : class
        {
            OAuthSession newSession = await _auth.RefreshAccessTokenAsync(request.Authorization).ConfigureAwait(false);
            AddAuthorization(request, newSession.AccessToken);
            return await _service.ToResponseAsync<T>(request).ConfigureAwait(false);
        }

Therefore, could it be, you are refreshing the access and refresh tokens when you identify an expired access token? If so, you are getting a new access and refresh tokens pair, but I never see nor get them; and my saved tokens are now invalid. Am I right? If so, how to workaround this? If I’m not right, why do you think I’m losing the authentication?

Thanks, Horacio.-

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Comments:23 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
brianytangcommented, Mar 5, 2014

Hi Horacio,

Just read the thread, and hopefully I can provide some clarity.

I see you’re creating a BoxClient and providing the auth session yourself. This leads me to believe that you are performing the OAuth workflow through some other means and retrieving the Access Token/Refresh Tokens from there. This should not be a problem and you are correct that the Access Token lasts 1 hour, and Refresh tokens last 60 days (ie. 2 months).

Using this newly created BoxClient within the hour should return proper responses and objects. I think where it may get confusing, is after that hour is up. If you continue to use this same BoxClient after the expiration period, on the first request, the SDK will detect that the Access Token has expired and attempt to refresh the session using the Refresh Token. If successful, it will maintain the new access token and refresh tokens in the AuthSession. This same process will happen after the new Access Tokens are expired.

The flow I described above should work for your purposes as a service, assuming that once the service is started, it is never stopped/restarted. If you restart the service, you will need to re create a new auth session for the Client to use as the session is not persisted. The simplest way to accomplish this is to persist the AccessToken/RefreshToken of the Auth Session when the app/service is closed. Then when the service is started again, you can recreate that same Auth Session with the persisted Access Token/Refresh Token. After the first request is made through the BoxClient, the SDK should detect if the Access Token is expired. If it is, it will attempt to refresh the tokens as mentioned before.

Hopefully that clarifies things. If you are using the exact flow as described above, and you are still coming across token expiration issues – please let us know.

Will wait for your response before closing this issue.

0reactions
ptallettcommented, Mar 24, 2017

Looks like this has been fixed:

  client = new BoxClient(config);
  client.Auth.SessionAuthenticated += Auth_SessionAuthenticated;
  session = await client.Auth.AuthenticateAsync(token);

… private async void Auth_SessionAuthenticated(object sender, SessionAuthenticatedEventArgs e) { // The SDK may refresh the tokens, so we have to save after every authentication https://github.com/box/box-windows-sdk-v2/issues/31 await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { AuthRepository repo = (AuthRepository)sender; SaveTokens(repo.Session.AccessToken, repo.Session.RefreshToken); }); }

Cheers, Paul

Read more comments on GitHub >

github_iconTop Results From Across the Web

What Are Refresh Tokens and How to Use Them Securely
The threat of illegitimate access is reduced as refresh tokens are continually exchanged and invalidated. For example, with refresh token ...
Read more >
OAuth2: Should a refresh token be invalidated after ...
When an API call fails with a 401, try to refresh the access token; When a token refresh fails, eg with a 401...
Read more >
Refresh token validation errors - Twitter Developers
Hi all, When using OAuth2 with PKCE for user access, I'm getting inconsistent errors from refresh tokens which is incredibly frustrating and ...
Read more >
Refresh Token Invalid
We recently updated our Application and I am getting an odd situation. I had to re-authorize and generate a new Access Token and...
Read more >
Refresh OAuth 2 Access token with Refresh Token failed. Body
If it returns invalid grant, the refresh token is pulled from the DB, decrypted and used to get new access AND refresh tokens....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found