This site uses cookies to deliver our services. By using this site, you acknowledge that you have read and understand our Cookie and Privacy policy. Your use of Kontext website is subject to this policy. Allow Cookies and Dismiss

OpenIddict Refresh Token Flow issue ASP.NET Core 2.0

1010 views 0 comments last modified about 10 months ago Raymond

In this page

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




Related pages

ASP.NET Core 2 with Bootstrap 4 Bundler Minifier Issue: Expected semicolon or closing curly-brace found '-'

561 views   1 comments last modified about 5 months ago

Background When upgrading Bootstrap to v4.0.0 release, the bundler and minifier doesn’t work properly due to CSS variable is commonly used: :root{--blue:#007bff; About 26 errors will show up in the Error List with the following message: ...

View detail

Issue - Unable to get property 'apply' of undefined or null reference occurred in Angular 4.*, VS2017 15.3, ASP.NET Core 2.0

6128 views   10 comments last modified about 2 years ago

Issue Context After installed Visual Studio 2017 15.3 preview and .net core 2.0 preview SDK, I upgraded one of my existing asp.net core project to 2.0. The project was created using ‘dotnet new angular’ SPA template.  I also upgraded all the client app packages to the latest. For exa...

View detail

Retrieve Http client request metadata like IP address and languages in asp.net core

799 views   0 comments last modified about 9 months ago

IP Address In ASP.NET Core, Request.UserHostAddress has been removed though that attribute exists in the traditional ASP.NET applications. We can use HttpContext.Connection to retrieve the remove client IP address: var ipAddress = HttpContext.Connecti...

View detail

Retrieve Identity username, email and other information in ASP.NET Core

656 views   0 comments last modified about 9 months ago

The identity system in ASP.NET has evolved over time. If you are using ASP.NET Core, you probably found User property is an instance of ClaimsPrincipal in Controller or Razor views. Thus to retrieve the information, you need to utilize the claims.

View detail

Retrieve Identity username, email and other information in ASP.NET Core

656 views   0 comments last modified about 9 months ago

The identity system in ASP.NET has evolved over time. If you are using ASP.NET Core, you probably found User property is an instance of ClaimsPrincipal in Controller or Razor views. Thus to retrieve the information, you need to utilize the claims.

View detail

Retrieve Azure AppSettings and Connection String Settings in ASP.NET Core Apps

1145 views   0 comments last modified about 9 months ago

In ASP.NET Core, we can easily use user secrets to manage our password or credentials. This post will summarize the approaches we can use after the websites are deployed into Azure.

View detail

Add comment

Please login first to add comments.  Log in New user?  Register

Comments (0)

No comments yet.