How to set session timeout / expiry time in ASP.NET Core MVC?

srinivas challa picture srinivas challa · Dec 18, 2019 · Viewed 8.8k times · Source

I am using ASP.NET Zero version 7 of ASP.NET Core, MVC and jQuery project.

I am trying to set session timeout / expiry time to automatically log out from the application when the application is idle for some time. Can anybody please let me know how to do this?

In ASP.NET Zero version 8, they are providing this configuration at User Management settings.

Answer

aaron picture aaron · Dec 18, 2019

ASP.NET Core MVC

Session expiry for MVC is provided via cookie by ASP.NET Core, independent of ASP.NET Zero.

Call ConfigureApplicationCookie after IdentityRegistrar.Register in Startup.cs:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // ...

    IdentityRegistrar.Register(services);                  // No change
    AuthConfigurer.Configure(services, _appConfiguration); // No change

    services.ConfigureApplicationCookie(o =>
    {
        o.ExpireTimeSpan = TimeSpan.FromHours(1);
        o.SlidingExpiration = true;
    });

    // ...
}

The defaults from ASP.NET Core v2.2.8 CookieAuthenticationOptions.cs#L30-L36:

public CookieAuthenticationOptions()
{
    ExpireTimeSpan = TimeSpan.FromDays(14);
    ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    SlidingExpiration = true;
    Events = new CookieAuthenticationEvents();
}

ASP.NET Zero (for ASP.NET Core)

ASP.NET Zero v7.2.0+ provides: