为什么用户在60分钟后使用Cookie身份验证自动注销

问题描述

我们有一个Blazor WASM应用程序,并希望通过Cookie-Authentication对用户进行身份验证。问题: 我们希望保留登录名30天,但用户将在60分钟后退出。我们尝试了多种配置,这些配置已发布到stackoverflow上,但没有成功。

Startup.cs(服务器端)

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
    // [...]
    options.SlidingExpiration = true;
    options.ExpireTimeSpan = System.TimeSpan.FromDays(30); // 30 Days
});

// [...]

public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
    // [...]

    app.UseAuthentication();
    app.UseAuthorization();

    // [...]
}

MyController.cs(服务器端)

public async Task<AuthResponse> Login(Credentials pCredentials)
{
    // [...]
    
    // set cookie
    await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(lClaimsIdentity),new AuthenticationProperties
    {
        IsPersistent = true,ExpiresUtc = DateTime.UtcNow.AddDays(30),// 30 Days
        RedirectUri = this.Request.Host.Value
    });

    // [...]
}

应用程序池(IIS)的高级设置:

application pool configuration

提示:我们使用[Authorize]属性来限制控制器。 60分钟后,当我们向任何受限制的控制器发出请求时,我们将获得一个http状态代码401。但是在浏览器中,auth-cookie仍然存在:

authentication cookie

问题:为什么用户在60分钟后退出

解决方法

我怀疑此问题与您的应用程序处于非活动状态并已关闭有关。这意味着当应用程序再次启动时,它将生成用于创建cookie的新密钥。您可以通过重新启动应用程序来进行测试,看看用户是否已注销。

我建议使用类似以下的方式来持久保存文件系统的密钥:

services.AddDataProtection()
   .SetApplicationName("IdentityServer")
   .PersistKeysToFileSystem(MyKeyPath);

这意味着身份验证会话也将在服务器重启后继续存在。

,

在IIS管理器(inetmgr)中,转到“应用程序池”>“高级设置”:

将IIS中的“空闲超时”设置为0,然后重新使用应用程序池。

IIS Idle Time-out

一天后,用户仍按预期登录。