2

I have an ASP.net core 3.1 MVC application that is using OpenID Connect with Identity Server 4. I am using IdentityModel to automatically refresh access tokens in my application. Configuration looks as follows:

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options =>
{    
    options.SlidingExpiration = false;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
})
.AddOpenIdConnect("oidc", options =>
{
    options.Authority = "https://localhost:5001";

    options.ClientId = "mvc";
    options.ClientSecret = "secret";
    options.ResponseType = "code";

    options.SaveTokens = true;

    options.Scope.Add("profile");
    options.Scope.Add("api1");
    options.Scope.Add("offline_access");
    options.GetClaimsFromUserInfoEndpoint = true;
    options.SignedOutCallbackPath = "/oidc-signout";
    options.SignedOutRedirectUri = "/goodbye";
});

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

services.AddHttpClient("api1", configure =>
{
    configure.BaseAddress = new Uri("https://localhost:6001");
});

services.AddAccessTokenManagement();

I have a controller that is going to pull data from a downstream API that is protected using that identity server. My MVC client requests scope api1 and offline_access to get refresh tokens. These tokens are stored in the cookie since SaveTokens = true is set on the services.

Everything is working fine. When I log in, I get the access token and refresh token. I have the access token last about 20 minutes, and when it expires it calls the token endpoint with the refresh token to get a new access token + refresh token.

The one scenario I'm not sure how to handle is when my refresh token lifetime has passed. If I set a refresh token lifetime for 8 hours, but my MVC session is still active it will attempt to get a new refresh token and fail.

Is there some event in the OpenID connect middleware I can handle that will detect when it fails to get this refresh token and can I use that to somehow force a login (or at least a round trip to the identity server /authorize endpoint) again?

Dismissile
  • 32,564
  • 38
  • 174
  • 263

1 Answers1

0

A solution I found is to hook that into the Cookies middleware. Here's the general flow:

On every request, use the Cookies middleware events to inspect the access token.

If it's close to its expiration time, request a new one.

Replace the new access and refresh tokens in the ClaimsIdentity.

Instruct the Cookies middleware to renew the session cookie so it contains the new tokens.

You can refer to this post, it may be helpful to you:What is intent of ID Token expiry time in OpenID Connect?

Tupac
  • 2,590
  • 2
  • 6
  • 19