会话注销过早

fos*_*bie 4 c# asp.net-identity asp.net-core

我将 ASP.NET Core 2.1 与 Microsoft Identity 一起使用,并且用户抱怨他们在仅大约 30 分钟不活动后就一直被重定向到登录屏幕。我在 ExpireTimeSpan 中设置了 60 分钟,但它永远不会持续那么长时间。有什么建议?

这是我在 Startup.cs 文件中的内容:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IRFDbRepository, RFDbRepository>();
    var connection = _configuration.GetConnectionString("RFDbConnection");
    services.Configure<ConnectionStrings>(_configuration.GetSection("ConnectionStrings"));
    services.AddDbContext<IdentityDbContext>(options => options.UseSqlServer(connection));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddRazorPagesOptions(options =>
    {
        options.AllowAreas = true;
        options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
    });

    services.AddIdentity<User, UserRole>().AddDefaultTokenProviders();
    services.AddTransient<IUserStore<User>, UserStore>();
    services.AddTransient<IRoleStore<UserRole>, RoleStore>();

    services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = "/Identity/Account/Login";
        options.LogoutPath = "/Identity/Account/Logout";
        options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
        options.SlidingExpiration = true;
    });
}
Run Code Online (Sandbox Code Playgroud)
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IRFDbRepository rFDbRepository)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    loggerFactory.AddFile(_configuration.GetValue<string>("Logging:LogFile"));
    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
        routes.MapRoute(
            name: "ActionApi",
            template: "api/{controller}/{action}/{id?}");
    });
}
Run Code Online (Sandbox Code Playgroud)

fos*_*bie 5

我终于找到了这个问题的根源。

ASP.NET Core 2.1 中的 Identity 存在一个问题,如果您实现了自己的 UserStore 版本而不是 IUserSecurityStampStore,则将跳过大多数有关安全标记的功能。

当您调用 AddIdentity() 时,它会每 30 分钟对 securityStamp 进行一次验证检查。

这会导致用户在 30 分钟后注销的令人困惑的行为,即使 cookie 没有过期。

显然 ASP.NET Core 2.2 中对此进行了修复,此处有更多详细信息

https://github.com/aspnet/Identity/issues/1880

同时,您可以让您的 UserStore 实现 IUserSecurityStampStore,或者通过将其添加到您的 startup.cs 将失败之间的时间从 30 分钟增加到 10 小时来执行我现在所做的快速修复。

services.Configure(o => o.ValidationInterval = TimeSpan.FromHours(10));