首页 > 解决方案 > 会话过早退出

问题描述

我正在使用带有 Microsoft Identity 的 ASP.NET Core 2.1,用户抱怨说,他们在闲置大约 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;
    });
}
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?}");
    });
}

标签: c#asp.net-coreasp.net-identity

解决方案


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

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));


推荐阅读