Course contentsShow
← C#
Lesson 1187 of 1,90811. Identity, Security, and ClaimsFree lesson

Managing Session Expiration and Absolute Timeouts

Implement sliding and absolute expiration policies to control authentication session lifetimes.

In this lesson, you will learn how to balance user convenience and application security by configuring sliding and absolute expiration policies for your authentication cookies.

Understanding Session Lifetimes

When a user logs into your ASP.NET Core application, they receive an authentication cookie. By default, this cookie lasts until the browser closes, but for professional applications, you need more granular control. We manage this using two primary concepts: Sliding Expiration and Absolute Timeout.

Sliding vs. Absolute Expiration

  • Sliding Expiration: Every time the user makes a request while their session is active, the system resets the cookie's expiration time. This provides a "keep-me-logged-in" experience for active users.
  • Absolute Timeout: This sets a hard limit on the lifetime of a session. Regardless of how active the user is, once this time limit is reached, the user is forced to re-authenticate.

Configuring Expiration in Startup

You configure these policies when setting up your Authentication services in your Program.cs or Startup.cs file. The CookieAuthenticationOptions class allows you to define these behaviors explicitly:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        // Enable sliding expiration so the clock resets on activity
        options.SlidingExpiration = true;

        // Set the window for the sliding expiration (e.g., 30 minutes)
        options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    });

To enforce an Absolute Timeout, you typically handle this by checking the IssuedUtc claim within your identity logic or by using a CookieAuthenticationEvents class to validate the ticket's age during the ValidatePrincipal event. By comparing the current time against the IssuedUtc property of the authentication ticket, you can reject the request if the session has existed longer than your security policy allows.

These settings are crucial for financial or sensitive applications where you want to ensure that a session cannot remain valid indefinitely simply by the user performing constant activity. By combining a 30-minute sliding window with a 4-hour absolute limit, you create a robust security barrier.

Key Takeaway: Use sliding expiration for user comfort during active sessions, but always enforce an absolute timeout to guarantee that session lifespans have a definitive security expiration point.