Search code examples
c#sessionasp.net-coreasp.net-identity

Session expire problem 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.

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 code

// 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?


Solution

  • 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