ASP.NET Core Interview Question #130

How does cookie authentication work in ASP.NET Core?

Authentication, Authorization & Security Mid-Level Intermediate

Quick Interview Answer

Cookie authentication stores an encrypted authentication ticket in a browser cookie after sign-in. On later requests, the cookie handler validates the ticket and reconstructs the user's ClaimsPrincipal.

Detailed Explanation

Cookie authentication stores an encrypted authentication ticket in a browser cookie after sign-in. On later requests, the cookie handler validates the ticket and reconstructs the user's ClaimsPrincipal.

Applications should configure secure cookie settings, expiration behavior, login/access-denied paths, and HTTPS appropriately. The cookie should contain identity information needed for authentication, not sensitive application data that should remain server-side.

Code Example

builder.Services.AddAuthentication("AppCookie")
    .AddCookie("AppCookie", options =>
    {
        options.LoginPath = "/Account/Login";
        options.AccessDeniedPath = "/Account/AccessDenied";
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    });