skip to content

In ASP.NET Core cookie authentication, how do ExpireTimeSpan, SlidingExpiration and AuthenticationProperties.IsPersistent decide how long a user stays signed in?

level: middleimportance: should knowfreq 48%

answer

  1. ticket expiry vs cookie expiry
  2. ExpireTimeSpan defaults to 14 days
  3. renew once past halfway
  4. IsPersistent writes an Expires attribute
  5. Cookie.Expiration fails options validation

basics

~20 s

ExpireTimeSpan (14 days) sets when the ticket inside the cookie expires. SlidingExpiration (on by default) re-issues the cookie once more than half that window has passed. IsPersistent decides whether the browser keeps the cookie after closing.

solid answer

~40 s

There are two clocks. The **ticket** inside the cookie carries `IssuedUtc` and `ExpiresUtc`; at sign-in `ExpiresUtc` becomes `IssuedUtc + ExpireTimeSpan` (14 days by default) unless `AuthenticationProperties.ExpiresUtc` is supplied, and the handler rejects an expired ticket on the server. The **browser cookie** is a session cookie unless `IsPersistent = true`, which gives it an `Expires` attribute equal to the ticket's expiry. `SlidingExpiration` (default `true`) re-issues the cookie with a fresh window when a request arrives after more than half the window has elapsed, keeping the original window length; `AllowRefresh = false` or `OnCheckSlidingExpiration` can stop that. Setting `options.Cookie.Expiration` is not the way: options validation rejects it with 'Cookie.Expiration is ignored, use ExpireTimeSpan instead.'

code

csharp · 14 lines
csharp
builder.Services
    .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Login";
        options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
        options.SlidingExpiration = true;
    });

// in the login handler
await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    principal,
    new AuthenticationProperties { IsPersistent = KeepMeSignedIn });

go deeper

for a junior

Know the two defaults, a 14-day ExpireTimeSpan and SlidingExpiration on, and that IsPersistent is the remember-me switch.

for a middle

Separate the ticket's server-checked expiry from the browser cookie's Expires attribute and explain the past-halfway renewal rule.

for a senior

Show how to add an absolute cap on top of sliding renewal, how AllowRefresh and OnCheckSlidingExpiration change renewal, and why Cookie.Expiration fails validation.

for a principal

Balance a short sliding window against user friction for different audiences, and decide where an absolute session limit is worth enforcing.

## Two expiries, not one People asking "how long does a cookie login last" usually mean one number, but ASP.NET Core's cookie handler keeps **two**: | Clock | Where it lives | Who enforces it | Set by | |---|---|---|---| | **Ticket expiry** | `ExpiresUtc` inside the protected ticket | the server, on every `AuthenticateAsync` | `ExpireTimeSpan` or `AuthenticationProperties.ExpiresUtc` | | **Cookie lifetime** | the `Expires` attribute of `Set-Cookie` | the browser | only written when `IsPersistent` is `true` | The server-side check is the one that matters for security: the handler compares `ExpiresUtc` with the current time and returns a failed result for an expired ticket, whatever the browser did with the cookie. ## The defaults `CookieAuthenticationOptions` sets, in its constructor: - `ExpireTimeSpan = TimeSpan.FromDays(14)` - `SlidingExpiration = true` At sign-in the handler stamps `IssuedUtc` (now) and, unless you passed `ExpiresUtc`, sets `ExpiresUtc = IssuedUtc + ExpireTimeSpan`. An `ExpiresUtc` passed in `AuthenticationProperties` overrides `ExpireTimeSpan` for that sign-in. ## IsPersistent: the "remember me" box `AuthenticationProperties.IsPersistent` controls only the browser side: - `false` (default): the cookie has no `Expires` attribute, so it is a session cookie that browsers usually drop when they close. The ticket inside still expires after `ExpireTimeSpan`. - `true`: the handler writes `Expires` equal to the ticket's `ExpiresUtc`, so the cookie survives a browser restart for up to 14 days by default. A parents' portal with a "Keep me signed in" checkbox maps the checkbox to `IsPersistent`; it does not need a second option. ## How sliding renewal works On each successful authentication the handler checks, when `SlidingExpiration` is on and the ticket's `AllowRefresh` is not `false`: 1. `elapsed = now - IssuedUtc`, `remaining = ExpiresUtc - now`. 2. If `remaining < elapsed` (more than half the window used), it marks the ticket for renewal; `OnCheckSlidingExpiration` can override that decision through `ShouldRenew`. 3. When the response starts, it writes a new cookie with `IssuedUtc = now` and `ExpiresUtc = now + (old ExpiresUtc - old IssuedUtc)`, so a custom 20-minute window slides as a 20-minute window. Consequences an interviewer probes: - With a 14-day window, an active user is re-issued a cookie at most about once a week, not on every request. - A user idle for longer than the whole window is signed out; there is no separate idle timer. - Sliding has no absolute cap of its own. An app that wants "never longer than 12 hours since sign-in" records the sign-in time as a claim or property and rejects older tickets in `OnValidatePrincipal`, or sets `AllowRefresh = false`. ## Settings that look right but are not - **`options.Cookie.Expiration`**: `AddCookie` registers an options validation that fails with "Cookie.Expiration is ignored, use ExpireTimeSpan instead." The handler also clears `Expires` from the built cookie options and computes it itself. - **`ISession` timeouts**: `SessionOptions.IdleTimeout` governs how long idle session state survives in the session middleware, which uses its own cookie and store; it has no effect on the sign-in. - **Short `ExpireTimeSpan` with sliding off**: users are signed out mid-task at a fixed time after login. ## Choosing values For the portal, a short window such as 30 minutes with sliding on gives an inactivity sign-out for parents on shared computers, while `IsPersistent` stays false unless the parent ticks the box. A partner API should not use cookies at all, which is why it gets its own scheme. ## What to say in the interview - Name both clocks before naming any number: the server-checked ticket and the browser-held cookie. - Quote the defaults (14 days, sliding on) and the half-window renewal rule. - Point out that sliding renewal re-stamps `IssuedUtc`, so "time since login" is lost unless you store it yourself. - Mention that a renewed cookie is only written on a response, so a user who sends no requests is never renewed and simply expires.

  • With ExpireTimeSpan of 30 minutes and sliding on, a parent makes requests at minute 10 and minute 20. When is the cookie re-issued?
    At minute 10, 10 minutes have elapsed and 20 remain, so nothing happens. At minute 20, 20 have elapsed and 10 remain, so remaining is less than elapsed and the handler writes a new cookie expiring at minute 50.
  • How would you cap a sliding cookie session at 12 hours since sign-in?
    Store the original sign-in time in the ticket, as a claim or an `AuthenticationProperties` item, and in `OnValidatePrincipal` call `RejectPrincipal()` and `SignOutAsync` once it is older than 12 hours. Sliding renewal keeps re-stamping `IssuedUtc`, so the original time must be kept separately.

  • Setting options.Cookie.Expiration is how you control the sign-in lifetime.
  • With IsPersistent false the ticket never expires while the browser stays open.
  • Sliding expiration re-issues the cookie on every single request.
  • The default cookie authentication lifetime is 20 minutes.
  • SessionOptions.IdleTimeout also shortens the authentication cookie.