Search code examples
c#authenticationasp.net-core-6.0

ASP.NET Core 6 project auto logout after 10~20 minutes


I Just Want to Know Why I Get Banned for Asking Questions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!???????????????????????????????????????????

This problem only exist in Online Host not Local Host.

On localhost, it's okay, but when I switch to online host that is Windows Host with Plesk (I think it is IIS but I'm not sure), user will get logged out after 10~20 minutes, no matter what I use - IsPersistent or not (keep user log in).

builder.Services.AddAuthentication("MyAuth").AddCookie("MyAuth", options =>
{
    options.Cookie.Name = "MyAuth";
    options.LoginPath = "/login";
    options.LogoutPath = "/logout";
    options.ExpireTimeSpan = TimeSpan.FromDays(30);
});

List<Claim> claims = new()
{
    new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()),
};

ClaimsIdentity identity = new(claims, "MyAuth");

ClaimsPrincipal principal = new(identity);

AuthenticationProperties properties = new() { IsPersistent = login.RememberMe };

await HttpContext.SignInAsync("MyAuth", principal, properties);

I don't know how to fix it. I searched a lot and most of tutorial is for ASP.NET Framework - not for ASP.NET Core.

What I tried:

  1. add options.SlidingExpiration = true; to AddAuthentication().AddCookie
  2. add builder.Services.Configure<SecurityStampValidatorOptions>(o => o.ValidationInterval = TimeSpan.FromHours(10)); to program.cs
  3. ExpiresUtc to AuthenticationProperties.

Update: I find this but don't know what to do? i can't find those setting is Plesk.

Mysterious Logout on IIS Server

Despite all of these settings you may experience that users are loging out after some minutes eg 20mins. Most probably you will not catch this behaviour on local while developing your application. It is related with some settings on IIS.

To fix this behaviour, first you need to go to advanced settings of application pool. You will see a setting called “Idle Time-out (minutes)” and must set as 0. Its default value is 20mins. It means that if no new request comes for 20 mins, worker process will be shut down.

When an app restarted or worker process restarted and If the keys related with authentication kept in memory;

Cookie based authentication tokens will be invalid and users will need to log in again.

So to keep keys persistent, we need to set one more setting on advanced settings of Application Pool; Load User Profile must be set to True. So keys will be stored in a folder on operation system. (%LOCALAPPDATA%/ASP.NET/DataProtection-Keys)


Solution

  • I found the solution. Just add this line of code before var app = builder.Build();:

    builder.Services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory())).SetDefaultKeyLifetime(TimeSpan.FromDays(30));