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

时间:2018-10-12 06:36:41

标签: c# asp.net-core asp.net-core-mvc

我正在将点网核心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 个答案:

答案 0 :(得分:0)

如果您希望该页面在空闲时自动注销用户,则必须添加一些js代码。它旨在跟踪中间时间,如果该时间比注销操作长于15秒。 最简单,重定向到注销操作。通过ajax调用注销并以响应方式显示登录模态,将更加有趣。 可以对Cookie设置进行调整,使其有效期超过15秒。想象一下,当空闲时间更长时,您希望拥有页面,通过在Cookie中进行严格设置,您将无法实现这一目标。