4

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:

NickG
  • 9,315
  • 16
  • 75
  • 115
  • These two, sessions and identities are not related. A *session* here is related to the session state container at the server side. Your identity expiration settings should be in the `UseCookieAuthentication` middleware configuration. – Wiktor Zychla Jul 22 '20 at 11:36
  • @WiktorZychla - I'm using .NET Core 3.1 so UseCookieAuthentication doesn't exist. – NickG Jul 22 '20 at 11:44
  • Yep, the config has been moved but still, these are two unrelated configs. – Wiktor Zychla Jul 22 '20 at 11:58

1 Answers1

5

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

NickG
  • 9,315
  • 16
  • 75
  • 115