会话在ASP.NET CORE 2.2 WEB APP中失效 [英] Session expire problen in ASP.NET CORE 2.2 WEB APP

查看:68
本文介绍了会话在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.

为此,我修改了startup.cs并创建了一个自定义的操作过滤器来处理会话到期,如果session为null,它将重定向到Login Action.

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代码

// 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" });
        });
    }

属性自定义代码

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

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

这篇关于会话在ASP.NET CORE 2.2 WEB APP中失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆