ASP.NET Core: session duration

Asked

Viewed 34 times

2

I did a program in ASP.NET Core MVC, which has the class Startup as:

    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.AddIdentity<AppUser, IdentityRole>()
                .AddEntityFrameworkStores<idDataContext>()
                .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(opts =>
            {
                opts.LoginPath = "/Account/Login";
                opts.AccessDeniedPath = "/Account/AccessDenied";
                opts.ExpireTimeSpan = TimeSpan.FromHours(4);
            });

            //...

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddMemoryCache();

            services.AddSession();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, AppFeatures features)
        {
            //...
            app.UseAuthentication();
            //...
            app.UseCookiePolicy();

            app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("error"))
                    throw new Exception("Erro: caminho contém 'error'!");

                await next();
            });

            app.UseSession();

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

            app.UseFileServer();
        }
    }

I am indicating that the login cookie and session cookie (with data from my app) last 4h? This is missing somewhere else?

It is that apparently the sessions do not last 4h in the client. There is some error?

Thank you.

1 answer

1


The session does not have an expiration like cookies, but it expires after a period of inactivity. The downtime starts to count after receiving the last request and each new request that passes through the session middleware restarts the time count. Its default limit is 20 minutes and can be set in option IdleTimeout. The IdleTimeout is used to determine how long a session can be idle before its content in the server cache is abandoned. This property is independent of the expiration of the cookie. To enable session middleware, your Startup must contain a IDistributedCache to store the session, a call to AddSession in ConfigureServices and a call to UseSession in Configure. For your case, a session that expires after 4 hours of inactivity with a cache configured in memory will look like the one below:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.ConfigureApplicationCookie(opts =>
        {
            opts.LoginPath = "/Account/Login";
            opts.AccessDeniedPath = "/Account/AccessDenied";
            opts.ExpireTimeSpan = TimeSpan.FromHours(4);
        });

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromHours(4);
            options.Cookie.HttpOnly = true;
            // Make the session cookie essential
            options.Cookie.IsEssential = true;
        });

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
            //...
            app.UseAuthentication();
            //...
            app.UseCookiePolicy();

            app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("error"))
                    throw new Exception("Erro: caminho contém 'error'!");

                await next();
            });

            app.UseSession();

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

            app.UseFileServer();
    }
}

note that the configuration options.IdleTimeout = TimeSpan.FromHours(4) was added in AddSession. For more information see microsoft official documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.