Search code examples
c#asp.netmodel-view-controllerrazor

ASP.NET MVC project kicks user out while using cookies


I am making an ASP.NET MVC web application using cookies. I have a login screen where I take username and password and there is a checkbox that remembers the user. If the user didn't check the checkbox, they should be forgotten upon closing the website. I can partially do this with the codes given below.

//A part of my AccessController/Login

if (loginViewModel.KeepLoggedIn) 
{
  authProperties = new AuthenticationProperties();
  {
    (IsPersistent = true), (ExpiresUtc = DateTimeOffset.UtcNow.AddDays(30));
  }
} 
else 
{
  authProperties = new AuthenticationProperties();
  {
    (IsPersistent = true), (ExpiresUtc = DateTimeOffset.UtcNow.AddSeconds(30));
  }
}

//Part of Program.cs where I create my cookie

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(option =>
    {
        option.EventsType = typeof(CustomCookieAuthenticationEvents);
        option.SlidingExpiration = true; // Renew the cookie on each request
        option.ExpireTimeSpan = TimeSpan.FromDays(30); // Remember me for 30 days
    });

With this when the user exits the website they will be forgotten in 30 seconds. However if the user stays idle in the website for more than 30 seconds, their next action will take them to the login screen. How do I fix this?

Thank you for your time.


Solution

  • The answer was changing IsPersistent to false and delete the ExpireUtc on the else statement. Afterwards, closing the whole browser -not just the tab your project is on- fixed the issue. Thanks to Wiktor Zychla.