Advertisement
Intermediate ASP.NET Core, Authentication

How does cookie-based authentication work in ASP.NET Core, and when is it preferred over token-based authentication?

Short answer

Cookie authentication issues an encrypted, signed cookie after successful login (via SignInAsync), which the browser automatically attaches to subsequent same-site requests; the server validates and decrypts it on each request to reconstruct the ClaimsPrincipal.

Save ASP.NET Core mock interview
Advertisement
AModel answer
Cookie authentication issues an encrypted, signed cookie after successful login (via SignInAsync), which the browser automatically attaches to subsequent same-site requests; the server validates and decrypts it on each request to reconstruct the ClaimsPrincipal. It's preferred for traditional server-rendered web applications (Razor Pages, MVC views) where the browser and server share the same origin, since it requires no client-side token management code and benefits from HttpOnly cookie protection against XSS token theft.
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => {
        options.LoginPath = "/Account/Login";
        options.ExpireTimeSpan = TimeSpan.FromHours(1);
    });

// After validating credentials:
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
Real-world example
A traditional server-rendered admin dashboard uses cookie authentication since the browser handles cookie attachment automatically, requiring no custom JavaScript token-management code compared to a JWT-based SPA architecture.
Likely follow-ups
  • Why is cookie authentication less suitable for a mobile app or cross-origin API?
  • How does the cookie's encryption key get managed across multiple server instances?
Related topics