Muhammed Yusuf
Muhammed Yusuf

Reputation: 156

.NET CORE Session Sliding Expiration Problem

my problem is I can not set sliding expiration configuration for session.

The Identity Cookie is sliding and not expiring while using the Application but the session not sliding, after IIS session timeout, the session is renewing itself and my session data is cleared.

Here is my startup code:

    public void ConfigureServices(IServiceCollection services)
    {
        // some other configurations..

        services.ConfigureApplicationCookie(options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromHours(6);
            options.LoginPath = "/Auth/Login";
            options.AccessDeniedPath = "/Dashboard";
            options.LogoutPath = "/Auth/Logout";
            options.SlidingExpiration = true;
            options.Cookie.IsEssential = true;
        });

        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromHours(6);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

    }

How to set sliding expiration property to session's cookie?

Upvotes: 2

Views: 2795

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239400

Your question is a little vague, but I think what you're referring to as "IIS session timeout" is actually the App Pool stopping and restarting. Based on that, you're likely using in-memory session storage, and since that's process-bound, your sessions go away when the App Pool does.

Under the hood, sessions utilize IDistributedCache for storage. The default provider for that is DistributedMemoryCache. Despite the name, it's not actually distributed; it's simply an implementation of IDistributedCache that uses memory, but still suffers from all the problems of any memory-based cache.

Long and short, you need a persistent distributed caching solution, such as SQL Server or Redis. See: https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.2#establish-distributed-caching-services.

Once you've set that up, your sessions, too, will be persistent, timing out only when they actually should.

Upvotes: 2

Related Questions