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

Posted

技术标签:

【中文标题】ASP.NET CORE 2.2 WEB APP中的会话过期问题【英文标题】:Session expire problem in ASP.NET CORE 2.2 WEB APP 【发布时间】:2020-03-11 17:33:42 【问题描述】:

我需要使会话过期,当用户尝试重用应用程序时将其送回登录页面。

为此,我修改了 startup.cs 并创建了一个自定义操作过滤器来处理会话过期,如果会话为空,它会重定向到登录操作。

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

在这种情况下,过期状态似乎不会出现。 我做错了什么?

【问题讨论】:

我不熟悉 ASP.NET Core,但是在经典的 ASP.NET 中,您会使用身份验证并使其在一定时间后过期。然后你不需要强制用户回到登录页面; ASP.NET 为您做这件事。我假设你可以在 ASP.NET Core 中做同样的事情。您不需要重新发明***。 【参考方案1】:

如果您想更改身份过期时间,只需使用

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

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

【讨论】:

【参考方案2】:

我很确定您不能多次调用 app.UseMvc(...)。

这样做可能会导致创建多层 MVC 框架。

相对首选的方法是在控制器或动作上使用 [Route("...")] 属性。

您也可以在 lambda 中重用 routes 参数。

参考Here

【讨论】:

没有办法集中管理超时吗?还有登录超时。 您能否通过用例示例更好地解释一下?

以上是关于ASP.NET CORE 2.2 WEB APP中的会话过期问题的主要内容,如果未能解决你的问题,请参考以下文章

将 Asp.Net Core 2.2 App 迁移到 3.1 时的整数序列化 [关闭]

使用 Web Deploy 在 Azure 中部署普通的 ASP.NET Core 2.2 Web 应用程序会引发错误

如何将 AzureAD 和 AzureADBearer 添加到 asp.net core 2.2 web api

如何测试返回 Ok(object) 的 ASP.NET Core 2.2 Web API GET IActionResult?

使用Http-Repl工具测试ASP.NET Core 2.2中的Web Api项目

在 Asp.Net Core App 中访问 Web.config 设置?