简体   繁体   English

ASP.NET CORE 2.2 WEB APP 中的 Session 过期问题

[英]Session expire problen in ASP.NET CORE 2.2 WEB APP

I need to expire the session, sending the user back to the Login page when he try to reuse the app.我需要使 session 过期,当用户尝试重用该应用程序时将其送回登录页面。

For this purpose I modified startup.cs and created a custom Action Filter that handles session expiration and if session is null, it redirects to Login Action.为此,我修改了 startup.cs 并创建了一个自定义操作过滤器来处理 session 过期,如果 session 是 null,它会重定向到登录操作。

startup.cs code startup.cs 代码

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

        string con1 = Configuration.GetConnectionString("EBBDatabase");
        services.AddDbContext<TelemetryWebContext>(options => options.UseSqlServer(con));

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


        //Session
        services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
        services.AddSession(options =>
        {
            options.Cookie.Name = ".Project.Session";
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromMinutes(3);
            options.Cookie.HttpOnly = true;
        });

        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });



        //identity
        services.AddIdentity<ApplicationUser, IdentityRole>()
             .AddEntityFrameworkStores<ebbxdbContext>()
             .AddDefaultTokenProviders();

        services.Configure<SecurityStampValidatorOptions>(options =>
        {
            options.ValidationInterval = TimeSpan.FromMinutes(3);
        });

        services.AddMvc(config =>
        {
            // using Microsoft.AspNetCore.Mvc.Authorization;
            // using Microsoft.AspNetCore.Authorization;
            var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


        services.AddAuthorization(options =>
        {
            options.AddPolicy("AllowingDevices", policy =>
                policy.Requirements.Add(new EBBDeviceRequirement(true)));
        });

        services.ConfigureApplicationCookie(options =>
        {
            options.AccessDeniedPath = "/Security/Error.html";

        });


        //custom classes
        services.AddHttpContextAccessor();
        services.AddTransient<ICookieService, CookieService>();
        services.AddTransient<IUserService, UserService>();
        services.AddTransient<IEmailService, EmailService>();
        services.AddTransient<IEncryption, Encryption>();
        services.AddTransient<INationsService, NationsService>();
        services.AddTransient<IDistrictsService, DistrictsService>();
        services.AddTransient<IProvincesService, ProvincesService>();
        services.AddTransient<ICityService, CityService>();
        services.AddTransient<IDeviceService, DeviceService>();
        services.AddTransient<IAddressService, AddressService>();
        services.AddTransient<ICustomerService, CustomerService>();
        services.AddTransient<IWebHelper, WebHelper>();
        services.AddTransient<IActivityLogService, ActivityLogService>();
        services.AddScoped<IAuthorizationHandler, EBBDeviceHandler>();

        AppSettings.AuthKey = Configuration.GetConnectionString("authKey");
        AppSettings.Collection = Configuration.GetConnectionString("collection");
        AppSettings.Collection2 = Configuration.GetConnectionString("collection2");
        AppSettings.Database = Configuration.GetConnectionString("database");
        AppSettings.Endpoint = Configuration.GetConnectionString("endpoint");
        AppSettings.SpName = Configuration.GetConnectionString("spName");
        AppSettings.SpNameDettaglio = Configuration.GetConnectionString("spNameDettaglio");
        AppSettings.KeyIoT = Configuration.GetConnectionString("KeyIoT");
        AppSettings.urlApi = Configuration.GetConnectionString("UrlApi");
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseSession();

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

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "alias_route_home",
                template: "Telemetries/Index",
                defaults: new { controller = "Telemetries", action = "Pagina2" });
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "alias_route_home_1",
                template: "Telemetries",
                defaults: new { controller = "Telemetries", action = "Pagina2" });
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "alias_route_events",
                template: "Events/Index",
                defaults: new { controller = "Events", action = "Pagina5" });
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "alias_route_events_1",
                template: "Events",
                defaults: new { controller = "Events", action = "Pagina5" });
        });
    }

attribute custom code属性自定义代码

public class SessionTimeoutAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = filterContext.HttpContext;
        if (!ctx.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new RedirectResult("~/Account/Login");
            return;
        }
        base.OnActionExecuting(filterContext);
    }
}

Using this scenario the expire status seems not appear.使用这种情况,过期状态似乎不会出现。 What I'm doing wrong?我做错了什么? Please help me.请帮我。

Simone西蒙娜

If you would like to change Identity expiration time, just use如果您想更改身份过期时间,只需使用

services.ConfigureApplicationCookie(options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromSeconds(5);
        });

Refer to https://forums.asp.net/t/2135963.aspx?ASP+NET+Core+2+with+Identity+Cookie+Timeouts参考https://forums.asp.net/t/2135963.aspx?ASP+NET+Core+2+with+Identity+Cookie+Timeouts

I am pretty sure you cannot call app.UseMvc(...) more than once.我很确定您不能多次调用 app.UseMvc(...) 。

Doing this will likely result in multiple layers of the MVC framework being created.这样做可能会导致创建多层 MVC 框架。

The relatively prefered method is to use [Route("...")] attributes on your controllers or actions.相对首选的方法是在控制器或操作上使用 [Route("...")] 属性。

alternatively you could, reuse the routes parameter in the lambda.或者,您可以重用 lambda 中的 routes 参数。

refer to Here参考这里

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

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