简体   繁体   English

用户空闲时间后Asp .net core自动注销

[英]Asp .net core auomatic logout after users idle time

I am using dot net core 2.0 with MVC.我在 MVC 中使用 dot net core 2.0。 I need to achieve this functionality.我需要实现这个功能。 If the user stays idle for 15 minutes i need to refresh and redirect to the login page.如果用户闲置 15 分钟,我需要刷新并重定向到登录页面。 I used Claims authentication.我使用了声明身份验证。 Here is what i have tried in starup.cs这是我在 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);" “options.ExpireTimeSpan = TimeSpan.FromSeconds(15);” is what I thought that will help me log out after 15 seconds (For testing purpose actually 15 minutes).是我认为这将帮助我在 15 秒后注销(出于测试目的,实际上是 15 分钟)。

Here is my entire start up这是我的整个启动过程

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

Can anyone help me achieve this.任何人都可以帮助我实现这一目标。

If you would like that page will automaticly logout user when idle, you have to add some js code.如果您希望该页面在空闲时自动注销用户,则必须添加一些js代码。 It purpose it to track iddle time and if it is longer then 15second than do logout action.它的目的是跟踪中间时间,如果它比注销操作长 15 秒。 Simplest, redirect to logout action.最简单,重定向到注销操作。 More fancy by ajax calling to logout and in response show login modal.通过 ajax 调用注销并作为响应显示登录模式更有趣。 Cookie setup can be tweak to be valid longer than 15seconds. Cookie 设置可以调整为有效时间超过 15 秒。 Imagine that you would like to have pages when idle time could be longer, with strict setting it in cookie you cannont achieve that.想象一下,当空闲时间可能更长时,您希望拥有页面,在 cookie 中对其进行严格设置是无法实现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM