OpenIddict Refresh Token Flow issue ASP.NET Core 2.0

access_time 4 years ago visibility2837 comment 0

Context

When I followed OpenIDDict refresh flow sample, I constantly got the issue “The refresh token is no longer valid”, which is returned by the following code in my authorization web api controller:

result.Content = new OpenIdConnectResponse
                     {
                         Error = OpenIdConnectConstants.Errors.InvalidGrant,
                         ErrorDescription = "The refresh token is no longer valid"
                     };

I checked the code and I can find that I followed all the steps in the following Git project:

https://github.com/openiddict/openiddict-samples/tree/dev/samples/RefreshFlow

In the service setup, I have also set the refresh token life time to be 30 days.

options.Configure(config =>
                 {
                     // Enable sliding expiration
                     config.UseSlidingExpiration = true;
                     // Set access token expiry time span
                     config.AccessTokenLifetime = TimeSpan.FromMinutes(60);
                     config.RefreshTokenLifetime = TimeSpan.FromDays(30);
                 });

‘Root Cause’

By looking into the following code, we can understand that if we cannot find the user principal via Principal property:

var user = await userManager.GetUserAsync(info.Principal);

So the root cause can be: the access token or the refresh token has expired. Since my refresh token life time is 30 days, the only possible cause is that: the access token has expired when it is doing refresh.

Resolution

Thus, I have implemented a session guard service in my Angular application. This service will regularly check whether access token is going to expire, if is, then call the token refresh authentication api to get the new tokens. The timing is quite important as you need to ensure that access token is valid when refreshing.

The following is the sample code in my Angular application:

checkSessionExpiring(time?: number) {
         /*If session is going to expire then refresh*/
         if (this.authService.isLoggedIn && this.authService.accessTokenExpiryDate != null) {
             if ((Date.now() + (Constants.TIMER_MILLISECONDS*2)) >= this.authService.accessTokenExpiryDate.valueOf()) {
                 if (!this.isRefreshing) {
                     this.isRefreshing = true;
                     console.log("Refreshing tokens as it is going to expire.");
                     this.authService.refreshLogin().subscribe(user => {
                         this.isRefreshing = false;
                     }, error => {
                         this.errorHnadler.handleEndpointResponseError(error);
                         this.isRefreshing = false;
                     });
                 };
             }
             else {
                 console.log('Session is active.');
             }
         }
     }

The True Root Cause

However, I didn't get this issue in asp.net 1.x, which means it still worked in 1.x if access token expired. That is the purpose that to use this refresh token. Root cause: we need to ensure SaveToken property is set to true when setting up OAuth authentication.

// Register the OAuth2 validation handler as required by oidc
             services.AddAuthentication(options =>
             {
                 options.DefaultAuthenticateScheme = OAuthValidationDefaults.AuthenticationScheme;
             }).AddOAuthValidation(options =>
             {
                 options.SaveToken = true;
             });




info Last modified by Raymond at 11 months ago copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

Want to publish your article on Kontext?

Learn more

Kontext Column

Created for everyone to publish data, programming and cloud related articles.
Follow three steps to create your columns.


Learn more arrow_forward

More from Kontext

local_offer asp.net core 2 local_offer asp.net core local_offer dotnetcore local_offer open-banking

visibility 253
thumb_up 0
access_time 2 years ago

I’ve just started an asp.net core 2.2 based implementation for Australia Consumer Data Standards (published by Data 61). Opening Banking initiative will follow these standards. The purpose is to help you to get familiar with these standards, especially the APIs that need to be implemented. The ...

local_offer .NET local_offer ASP.NET local_offer asp.net core 2 local_offer dotnetcore

visibility 703
thumb_up 0
access_time 4 years ago

Before Visual Studio 2017 was released, I was implementing my ASP.NET Core project using VS2015. TFS2015 is used for Continuous Build and Deployment for my projects. After migrating to VS2017, there are couple of issues I encountered in my environment: VS2017 has abounded the JSON project file ...

local_offer asp.net core 2 local_offer dotnetcore

visibility 2308
thumb_up 0
access_time 4 years ago

Migrating from ASP.NET Core 1.x to 2.0 is not an easy job especially if you have customized Identity and used customized authentication. This post summarizes the issues and errors I have experienced and their resolutions when upgrading my project. Hopefully it can save you sometime if you are doing ...

About column

Articles about ASP.NET Core 1.x, 2.x and 3.x.

rss_feed Subscribe RSS