📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does cookie authentication work in ASP.NET Core? Explain what is inside the authentication cookie, the HttpOnly, Secure and SameSite flags, absolute vs sliding expiry, and the role Data Protection keys play.

Cookie authentication in ASP.NET Core: the encrypted ticket, cookie flags, expiry settings, server-side session stores and Data Protection keys.

Junior Theory Beginner aspnet-core authentication cookies data-protection samesite security

🎯 Key points

  • SignInAsync serialises the ClaimsPrincipal into a ticket encrypted with Data Protection
  • HttpOnly blocks JavaScript access; Secure sends only over HTTPS; SameSite=Lax by default
  • ExpireTimeSpan default 14 days; SlidingExpiration reissues after half the window
  • IsPersistent decides session cookie vs persistent cookie
  • Large tickets are chunked; ITicketStore keeps the ticket server-side
  • Shared Data Protection key ring needed across instances
  • Revocation needs OnValidatePrincipal or security stamp validation

⏱ 30-second answer

After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.

  • Flags: HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).
  • Expiry: ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.
  • Keys: every instance must share the Data Protection key ring, or cookies issued by one server can't be read by another.

The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.

🗣 Full answer (senior)

How I would answer this in an interview

"Cookie authentication is the classic browser model. When the user logs in, the app builds a ClaimsPrincipal and calls SignInAsync with the cookie scheme. The handler serialises the claims and properties into an authentication ticket, protects it with ASP.NET Core Data Protection, which is authenticated encryption, and writes it to a cookie, by default .AspNetCore.Cookies. The browser sends it back automatically, and on each request the handler unprotects it and rebuilds the user. If anyone edits the cookie, decryption fails and the request is anonymous.

The flags matter. HttpOnly is on by default, so injected script can't steal the cookie. Secure should be Always, so it never travels over plain HTTP. SameSite defaults to Lax, which stops the cookie being sent on cross-site POSTs and is a strong CSRF mitigation, although not a replacement for antiforgery tokens. Expiry has two parts: the ticket's own expiry, ExpireTimeSpan, 14 days by default, and with SlidingExpiration the handler reissues the cookie when more than half of that time has passed, so active users stay signed in. IsPersistent on the sign-in properties controls whether the browser keeps it after closing.

The mistake I see is forgetting that the ticket is encrypted with keys that live somewhere. With two App Service instances and the default key storage, users are randomly logged out, and after every deployment everyone is. The senior line: a cookie ticket is a bearer credential you can't take back, so you either keep it short, validate it against a security stamp, or store the ticket server-side."


Cookie flags

Flag Default in ASP.NET Core What it prevents
HttpOnly true document.cookie theft through XSS
Secure (CookieSecurePolicy) SameAsRequest Sending the cookie over HTTP; set Always
SameSite Lax Cookie on cross-site POSTs, iframes and fetches (CSRF)
Path / Domain /, host only Leaking to other paths or subdomains

Expiry options

Setting Effect
ExpireTimeSpan Lifetime of the ticket inside the cookie (default 14 days)
SlidingExpiration Reissue when more than half the lifetime has elapsed (default true)
IsPersistent false: session cookie, gone when the browser closes; true: persistent cookie
ExpiresUtc Absolute end you set at sign-in; sliding never extends past what you validate

What happens on each request

  1. Read the cookie (reassembling chunks if the ticket was larger than ~4 KB).
  2. Unprotect it with the Data Protection key named in its header.
  3. Check expiry; optionally run OnValidatePrincipal (Identity uses this for the security stamp).
  4. Set HttpContext.User; renew the cookie if sliding expiry applies.

Production example

On a [company] staff portal we had 3 instances and keys stored on the local file system. About [one in three] requests from a user landed on an instance that couldn't decrypt their cookie, so they bounced to login. Persisting keys to Blob Storage, protected with a Key Vault key, dropped unexpected sign-outs from [~200 a day] to [zero].

🔍 What the interviewer is checking

Checks that the candidate knows what the cookie actually contains and the operational consequences (keys, revocation), not just how to call AddCookie.

Green flags

  • Explains the encrypted ticket and that no session store is needed by default
  • Knows the three flags and their defaults
  • Connects multi-instance sign-outs to Data Protection keys
  • Mentions how to revoke a session

Red flags

  • Thinks the cookie holds a session id looked up in a database by default
  • Believes SameSite alone makes CSRF impossible
  • Never mentions HTTPS

📚 Learn in depth

1. The ticket

ClaimsPrincipal + AuthenticationProperties (IssuedUtc, ExpiresUtc, IsPersistent, items)
   -> TicketSerializer (binary)
   -> IDataProtector(purpose: "...CookieAuthenticationMiddleware", scheme, "v2")
   -> base64url -> Set-Cookie: .AspNetCore.Cookies=CfDJ8...

The CfDJ8 prefix you often see is the Data Protection magic header and version. Every claim you add makes the cookie bigger; above about 4 KB the ChunkingCookieManager splits it into .AspNetCore.CookiesC1, C2 and so on, which is a sign you are storing too much.

2. Data Protection

Data Protection gives authenticated encryption (AES-256-CBC + HMACSHA256 by default) with a key ring. Keys rotate every 90 days by default; old keys stay for decryption. The default storage depends on the host (for example the user profile, or a folder on Azure App Service that is shared across instances of the same app but not across slots). In containers the default is inside the container, so keys vanish on restart. Production apps call PersistKeysToAzureBlobStorage and ProtectKeysWithAzureKeyVault, and set SetApplicationName so all instances agree.

3. Revocation

A self-contained cookie is valid until it expires. Options:

short ExpireTimeSpan + sliding     -> exposure window bounded
OnValidatePrincipal / SecurityStamp -> check a stamp every N minutes (Identity: 30 by default)
ITicketStore (SessionStore)        -> cookie holds only a key; delete the row to revoke

ITicketStore with a distributed cache gives server-side sessions: small cookies and immediate revocation, at the cost of a cache lookup per request.

4. Cookies and APIs

Cookies are sent automatically by the browser, which is what makes CSRF possible. For same-site SPAs a cookie-based BFF is still the safest pattern, because tokens never reach JavaScript. Since .NET 10, cookie authentication returns 401/403 rather than redirecting to the login page for known API endpoints.

Try it yourself

  1. Sign in to a sample app and inspect the cookie in browser dev tools: note the flags and size.
  2. Add 50 claims and watch the cookie split into chunks.
  3. Run two instances behind a local YARP proxy with default key storage, then fix it with a shared key directory.
  4. Implement OnValidatePrincipal that rejects users whose SecurityStamp changed, and test it by changing a password.
  5. Plug in an ITicketStore backed by IDistributedCache and compare cookie size before and after.

💻 Code

Cookie authentication with hardened flags, shared Data Protection keys and a sign-in endpoint.

// Program.cs (.NET 10)
using System.Security.Claims;
using Azure.Identity;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;

var builder = WebApplication.CreateBuilder(args);

// Every instance must read and write the same key ring.
builder.Services.AddDataProtection()
    .SetApplicationName("staff-portal")
    .PersistKeysToAzureBlobStorage(new Uri(builder.Configuration["DataProtection:BlobUri"]!), new DefaultAzureCredential())
    .ProtectKeysWithAzureKeyVault(new Uri(builder.Configuration["DataProtection:KeyUri"]!), new DefaultAzureCredential());

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Name = "__Host-portal";              // __Host- prefix: Secure, no Domain, Path=/
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.Cookie.SameSite = SameSiteMode.Lax;
        options.ExpireTimeSpan = TimeSpan.FromHours(8);     // a working day, not 14 days
        options.SlidingExpiration = true;
        options.LoginPath = "/login";
    });
builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapPost("/login", async (LoginRequest request, HttpContext http, CancellationToken ct) =>
{
    // Password verification omitted: use ASP.NET Core Identity or an IdP in real code.
    var identity = new ClaimsIdentity(
        [new Claim(ClaimTypes.NameIdentifier, "42"), new Claim(ClaimTypes.Name, request.UserName)],
        CookieAuthenticationDefaults.AuthenticationScheme);

    await http.SignInAsync(new ClaimsPrincipal(identity),
        new AuthenticationProperties { IsPersistent = request.RememberMe });
    return Results.NoContent();
}).AllowAnonymous();

app.Run();

public sealed record LoginRequest(string UserName, string Password, bool RememberMe);

⚠ Common mistakes

  • Mistake: Leaving SecurePolicy at SameAsRequest behind a TLS-terminating proxy. Why it is wrong: the app sees HTTP, so the cookie is issued without Secure. Instead: use CookieSecurePolicy.Always and configure forwarded headers.
  • Mistake: Keeping Data Protection keys in the default location in containers or across several instances. Why it is wrong: cookies fail to decrypt on other instances and after every restart. Instead: persist keys to Blob Storage or a database and protect them with Key Vault.
  • Mistake: Putting large data (permissions lists, profile data) in claims. Why it is wrong: the cookie grows, gets chunked and is sent on every request, including static files. Instead: keep a few identifying claims; look up the rest or use an ITicketStore.
  • Mistake: Using the 14-day default for a sensitive app. Why it is wrong: a stolen cookie works for two weeks. Instead: choose a lifetime that matches the risk and add re-authentication for sensitive actions.
  • Mistake: Assuming SameSite=Lax removes the need for antiforgery tokens. Why it is wrong: same-site requests from a compromised subdomain and top-level GETs are still allowed. Instead: keep antiforgery validation on state-changing forms.
  • Mistake: Expecting sign-out to invalidate copies of the cookie. Why it is wrong: SignOutAsync only deletes the browser's cookie; a stolen copy still decrypts. Instead: validate a security stamp or use server-side tickets when revocation matters.

🏛 Senior insight: trade-offs

The cookie handler is a good default for anything a browser talks to directly: HttpOnly cookies keep credentials out of JavaScript, which is why the BFF pattern exists. Its weakness is revocation. Decide up front how quickly a disabled account must lose access, and pick the mechanism from that number.

Option When it fits Cost When not to
Self-contained cookie, short lifetime Internal tools, low-risk apps None at runtime When admins must kill sessions instantly
Security stamp validation (OnValidatePrincipal) ASP.NET Core Identity apps A DB read every validation interval Very high request rates without caching
ITicketStore server-side sessions Banking, health, government A cache lookup per request; cache must be highly available Simple sites where the cookie size is fine

Measure cookie size in the browser and watch for unexpected 302s to the login page in Application Insights; a jump after a deployment almost always means the key ring.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says cookies are self-contained Why: Checks they understand revocation of bearer credentials
    How to answer

    A self-contained cookie stays valid until it expires, so you add a server-side check. CookieAuthenticationEvents.OnValidatePrincipal runs on every authenticated request and is where custom checks go: look up the user (cached) and call context.RejectPrincipal() plus SignOutAsync if they are disabled or their session was revoked. ASP.NET Core Identity's SecurityStampValidator plugs into that event: every ValidationInterval (30 minutes by default; lower it for sensitive apps) it compares the cookie's security stamp with the database and rejects the cookie if the stamp changed. Identity changes the stamp on password, MFA and email changes; call UpdateSecurityStampAsync when an admin disables a user. For truly immediate revocation, set CookieAuthenticationOptions.SessionStore to an ITicketStore backed by a distributed cache: the cookie then holds only a session key, and deleting the server-side entry ends the session on the next request.

  2. When: Candidate mentions the app running behind a reverse proxy Why: Checks that they know why Secure cookies and redirects break behind TLS termination
    How to answer
    • A forward proxy sits in front of clients (corporate egress proxy): clients send requests through it to the internet. For HTTPS it tunnels with CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.
    • A reverse proxy sits in front of servers (nginx, Envoy, YARP, App Gateway, ingress): it terminates TLS, routes, load balances, caches and adds headers.

    Behind a reverse proxy, the app sees the proxy's IP and often plain http. The proxy passes the originals in X-Forwarded-For and X-Forwarded-Proto, but ASP.NET Core only applies them via the ForwardedHeaders middleware, and by default only trusts proxies on loopback. So UseHttpsRedirection sees http, redirects to https, the proxy forwards as http again: a loop.

    Fix: UseForwardedHeaders first, configured with the proxy's IPs or network in KnownProxies/known networks. Do not trust all sources, or clients can spoof their IP and scheme.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me