ASP.NET Core自动在用户闲置时间后注销

5

我正在使用dot net core 2.0和MVC。我需要实现以下功能:如果用户闲置15分钟,我需要刷新并重定向到登录页面。我使用了Claims身份验证。以下是我在starup.cs中尝试的代码:

services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            //options.Cookie.Expiration = TimeSpan.FromDays(150);
            options.ExpireTimeSpan = TimeSpan.FromSeconds(15);
            options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
            options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
            options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
            options.SlidingExpiration = true;
        });

"

options.ExpireTimeSpan = TimeSpan.FromSeconds(15);

"是我认为可以帮助我在15秒后注销(实际上是用于测试目的的15分钟)。
以下是整个启动过程:
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>(config =>
        {
            config.SignIn.RequireConfirmedEmail = false;
        })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        services.AddScoped<UserManager<ApplicationUser>>();
        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = false;
            options.Password.RequiredUniqueChars = 6;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.Lockout.AllowedForNewUsers = true;

            // User settings
            options.User.RequireUniqueEmail = true;

        });
        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            //options.Cookie.Expiration = TimeSpan.FromDays(150);
            options.ExpireTimeSpan = TimeSpan.FromSeconds(15);
            options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
            options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
            options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
            options.SlidingExpiration = true;
        });


        services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));

        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        //Common Services
        services.AddTransient<CommonService, CommonService>();
        services.AddMvc()
                        .AddJsonOptions(options =>
        options.SerializerSettings.ContractResolver = new DefaultContractResolver());

        services.Configure<AppSettings>(Configuration.GetSection("ApplicationSettings"));
        // Add Kendo UI services to the services container
        services.AddKendo();

        //Date Format
        services.Configure<DateSettings>(Configuration.GetSection("DateSettings"));

        //Templates
        services.Configure<Templates>(Configuration.GetSection("Templates"));

        //Themes
        services.Configure<ThemeSettings>(Configuration.GetSection("ThemeSettings"));

        //Title
        services.Configure<TitleSettings>(Configuration.GetSection("TitleSettings"));

        //Google reCaptcha
        services.Configure<GoogleReCaptcha>(Configuration.GetSection("GoogleReCaptcha"));

        services.Configure<LoginAttemptsToCaptcha>(Configuration.GetSection("LoginAttemptsToCaptcha"));
        services.Configure<PhysicalExamination>(Configuration.GetSection("PhysicalExamination"));

        //Reset Password Settings
        //var reset = services.Configure<ResetPasswordSettings>(Configuration.GetSection("ResetPasswordSettings"));
        var resetsettingsSection = Configuration.GetSection("ApplicationSettings");
        var settings = resetsettingsSection.Get<AppSettings>();

        services.Configure<DataProtectionTokenProviderOptions>(options =>
        {
            options.TokenLifespan = TimeSpan.FromMinutes(settings.ResetPasswordExpiryTime);
        });

        //services.AddMvc().AddSessionStateTempDataProvider();
        //services.AddSession();
        //services.AddSession(options =>
        //{
        //    options.IdleTimeout = TimeSpan.FromSeconds(10);
        //});
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, 
        IHostingEnvironment env,
        UserManager<ApplicationUser> userManager,
        RoleManager<ApplicationRole> roleManager, ApplicationDbContext context)

    {

        //app.UseMiddleware<AuthenticationMiddleware>();
        //app.UseMiddleware<ErrorHandlingMiddleware>();
        app.UseAuthenticationMiddleware();
        if (env.IsDevelopment())
        {
            //app.UseBrowserLink();
            //app.UseDeveloperExceptionPage();
            //app.UseDatabaseErrorPage();
            //app.UseExceptionHandler("/Home/Error");
        }
        else
        {
            //app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();

        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            if (!serviceScope.ServiceProvider.GetService<ApplicationDbContext>().AllMigrationsApplied())
            {
                serviceScope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
            }
            AppIdentityDataInitializer.SeedAdminUser(userManager, roleManager, context);
            serviceScope.ServiceProvider.GetService<ApplicationDbContext>().EnsureSeeded();
        }

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
        // Configure Kendo UI
        //app.UseKendo(env);

        //app.UseSession();
    }
}

有没有人能帮我实现这个。


1
这里到底有什么问题?它不需要重新登录吗? - Sami Kuhmonen
会话仍然有效。 - Sam Daniel
你的代码对我来说完美无缺。能否请您展示一下startup.cs的完整代码? - itminus
你是否在 ApplicationBuilder 上自定义了一个扩展方法 UseAuthenticationMiddleware()?你的 UseAuthenticationMiddleware 方法中有什么线索吗? - itminus
@itminus 我没有定制任何扩展。 - Sam Daniel
显示剩余7条评论
1个回答

1
如果您希望页面在闲置时自动注销用户,则需要添加一些js代码。它的目的是跟踪空闲时间,如果超过15秒,则执行注销操作。 最简单的方法是重定向到注销操作。更高级的方法是通过ajax调用注销,并在响应中显示登录模态框。 可以调整Cookie设置以使其有效期长于15秒。想象一下,如果您希望页面的闲置时间更长,那么通过严格设置Cookie,您将无法实现这一点。

最好详细说明一下。添加一些代码、示例等。 - mate00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接