How to handle cookie expiration in asp.net core

I would like to know how to properly handle the fact that a cookie has expired? Is it possible to perform a custom action?

What I would like to achieve is that when the cookie has expired, you need to get some information from the current cookie when redirecting to the action parameter for this information. Is it possible?

+1
asp.net-mvc asp.net-core asp.net-core-mvc asp.net-identity
source share
3 answers

It looks like you need your own handler for OnValidatePrincipal when setting up the cokies middleware:

The OnValidatePrincipal event can be used to intercept and override cookie ID validation.

app.UseCookieAuthentication(options => { options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = <your event handler> }; }); 

The documentation contains an example of such a descriptor:

 public static class LastChangedValidator { public static async Task ValidateAsync(CookieValidatePrincipalContext context) { // Pull database from registered DI services. var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>(); var userPrincipal = context.Principal; // Look for the last changed claim. string lastChanged; lastChanged = (from c in userPrincipal.Claims where c.Type == "LastUpdated" select c.Value).FirstOrDefault(); if (string.IsNullOrEmpty(lastChanged) || !userRepository.ValidateLastChanged(userPrincipal, lastChanged)) { context.RejectPrincipal(); await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance"); } } } 
+1
source share

Impossible to do this. If the cookie has expired, it is not sent to the server to retrieve any information. With ASP.Net Core Identity, you don't have much control over this. This gives you the ability to use cookie middleware.

This gives the user a normal redirect when the cookie expires:

 public void ConfigureServices(IServiceCollection services) { services.Configure<CookieAuthenticationOptions>(options => { options.LoginPath = new PathString("/Home/Index"); }); } 

The best way to achieve what you are looking for is to set the cookie expiration much later than the expiration of the authentic user session, and then run the server expiration session command and redirect the user at that point. Although this is not ideal, you have no other options when the cookie has expired.

 public void ConfigureServices(IServiceCollection services) { app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = "MyCookieMiddlewareInstance", // Redirect when cookie expired or not present LoginPath = new PathString("/Account/Unauthorized/"), AutomaticAuthenticate = true, // never expire cookie ExpireTimeSpan = TimeSpan.MaxValue, Events = new CookieAuthenticationEvents() { // in custom function set the session expiration // via the DB and reset it everytime this is called // if the session is still active // otherwise, you can redirect if it invalid OnValidatePrincipal = <custom function here> } }); } 
+1
source share

There seems to be no event for your case, but you can use OnRedirectToLogin to change the uri redirect. Here is an example:

 OnRedirectToLogin = async (context) => { var binding = context.HttpContext.Features.Get<ITlsTokenBindingFeature>()?.GetProvidedTokenBindingId(); var tlsTokenBinding = binding == null ? null : Convert.ToBase64String(binding); var cookie = context.Options.CookieManager.GetRequestCookie(context.HttpContext, context.Options.CookieName); if (cookie != null) { var ticket = context.Options.TicketDataFormat.Unprotect(cookie, tlsTokenBinding); var expiresUtc = ticket.Properties.ExpiresUtc; var currentUtc = context.Options.SystemClock.UtcNow; if (expiresUtc != null && expiresUtc.Value < currentUtc) { context.RedirectUri += "&p1=yourparameter"; } } context.HttpContext.Response.Redirect(context.RedirectUri); } 
0
source share

All Articles