Logout user after inactivity in asp.net core

Viewed 7074

I am new to asp.net core. I am trying to implement User Logout after being inactive for a period of time. Can someone suggest guide/tutorial or explain how to implement this using asp.net core 2.0 and MySql instead of Entity Framework.

2 Answers

After configuring your identity in the services using AddIdentity or AddDefaultIdentity you can configure your cookie ExpireTimeSpan

You could read Cookie Settings block in the linked article.

services.ConfigureApplicationCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
    options.LoginPath = "/Identity/Account/Login";
    options.SlidingExpiration = true;
});

ExpireTimeSpan is the TimeSpan after which the cookie will expire. SlidingExpiration will instruct the handler a new cookie with new expiration time.

Here documentation:

Summary: The SlidingExpiration is set to true to instruct the handler to re-issue a new cookie with a new expiration time any time it processes a request which is more than halfway through the expiration window.

services.ConfigureApplicationCookie(options =>
 {
 options.LoginPath = "/Identity/Account/Login";
 options.LogoutPath = "/Identity/Account/Logout";
 options.AccessDeniedPath = "/Identity/Account/AccessDenied";
 options.ExpireTimeSpan = TimeSpan.FromSeconds(60);
  options.SlidingExpiration = true;
            }); 

In .net core 3+ the examples show '$' on the login path and logout. This caused errors when running on lunix. Just remove the '$' and the above worked for me.

Related