Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 3.1 / Identity session never expires. How can I get it to expire on sliding expiration?

A security check of my website showed that sessions (i.e. login) never expire. I've tested myself and I find the same - I opened up the site on localhost this morning and I'm still signed in from yesterday. I always assumed it would expire after 20 minutes like it would in .NET Framework apps.

I'm using the ASP.NET Core Identity scaffolding with minimal changes other than implementing two factor authentication.

enter image description here

In my Startup.cs I have the following code to add session support:

services.AddSession(options =>
{
    options.Cookie.IsEssential = true;
    options.IdleTimeout = TimeSpan.FromSeconds(10);
    options.Cookie.Expiration = TimeSpan.FromSeconds(10);
});

I can't see any code relating to login timout under IdentityOptions.

On the login page, I'm specifically hardcoding any "remember me" type function to false:

await _signInManager.SignInWithClaimsAsync(user, isPersistent: false, claims);

How can I make my login sessions expire after ~20 minutes like they do automatically in .NET Framework?

I basically have the exact opposite problem to the one mentioned in this question: asp.net-core2.0 user auto logoff after 20-30 min

Most questions on here seems to be asking how to increase the timeout, but I need it decreased from (seemingly) infinite to 20 minutes or so:

like image 663
NickG Avatar asked Aug 30 '25 15:08

NickG


1 Answers

I found that I had to add the following code in Startup.cs to set the ApplicationCookie expiration time:

services.ConfigureApplicationCookie(options => options.ExpireTimeSpan = TimeSpan.FromMinutes(20));

I tested it using .FromSeconds(10) first and I get logged out after 10 seconds.

The documentation for this function is here: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-3.1#cookie-settings

like image 87
NickG Avatar answered Sep 02 '25 05:09

NickG