Search code examples
c#asp.net-coreasp.net-core-identity

asp.net core 2.2 razor page login not persistent. very soon user must re login


user after login very soon exit and must be re login.

i want user persistent in site for 30 minutes after login.

in startup:

services.Configure<CookiePolicyOptions>(options =>
{
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => false;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
    options.Password.RequiredLength = 5;
})
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// Configure your policies
services.AddAuthorization(options =>
    options.AddPolicy("PanelPolicy", policy =>
        policy.RequireRole("admin")
));

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Expiration = TimeSpan.FromMinutes(30);
        options.SlidingExpiration = true;
    });

and in login page:

var result = await _signInManager.PasswordSignInAsync(user.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
    _logger.LogInformation("User logged in.");
    return LocalRedirect(returnUrl);
}

but after short second user must re login to site


Solution

  • i using shared hosting. When the program in iis is restarted, a new key is created. Therefore the previous token becomes invalid. So we have to manage the key to be valid with the reset

    this line solve my problem

    services.AddDataProtection()
                .PersistKeysToFileSystem(new DirectoryInfo(_hostingEnvironment.ContentRootPath))