In ASP.NET Core, how does cookie sign-in with AddCookie and HttpContext.SignInAsync work, and how is HttpContext.User filled on the next request?
answer
- you verify the password, not the handler
- ClaimsIdentity needs an authentication type
- ticket protected by Data Protection
- cookie named .AspNetCore.Cookies
- default authenticate scheme sets HttpContext.User
basics
~20 sAddCookie registers a handler; SignInAsync turns a ClaimsPrincipal into a protected ticket and writes it as a cookie. On later requests the authentication middleware asks the default scheme to read that cookie and sets HttpContext.User from it.
solid answer
~40 sYou register the scheme with `AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(...)`. The cookie handler never checks a password: your login page does that, then builds `Claim`s, wraps them in a `ClaimsIdentity` **with an authentication type** (otherwise `IsAuthenticated` is false and `SignInAsync` throws, because `AuthenticationOptions.RequireAuthenticatedSignIn` defaults to `true`) and calls `HttpContext.SignInAsync(scheme, new ClaimsPrincipal(identity))`. The handler serializes an `AuthenticationTicket`, protects it with Data Protection and appends it as a cookie named `.AspNetCore.Cookies`. Nothing is stored on the server by default. On the next request the authentication middleware calls `AuthenticateAsync` for the default authenticate scheme; the handler unprotects the cookie, checks the ticket's expiry and the principal becomes `HttpContext.User`. `SignOutAsync` deletes the cookie.
code
csharp · 9 linesbuilder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Login";
options.AccessDeniedPath = "/Denied";
});
builder.Services.AddAuthorization();
builder.Services.AddRazorPages();go deeper
Recall the three calls in order: register the scheme with AddCookie, verify the user yourself, then SignInAsync with a ClaimsPrincipal; SignOutAsync removes the cookie.
Explain what travels in the cookie, why the identity needs an authentication type, and why User is only populated on the following request by the default authenticate scheme.
Discuss what a stateless ticket means for sign-out and revocation, cookie size from too many claims, and when a SessionStore or OnValidatePrincipal check is worth its cost.
Weigh a self-contained cookie ticket against server-held tickets across instances: shared Data Protection keys versus a shared ticket store, and what each means for revoking a compromised account.
## The moving parts Cookie authentication in ASP.NET Core is a **scheme**: a name (`"Cookies"`, the value of `CookieAuthenticationDefaults.AuthenticationScheme`) bound to a **handler** (`CookieAuthenticationHandler`) and its options (`CookieAuthenticationOptions`). Your code never talks to the handler directly; it calls extension methods on `HttpContext` that go through `IAuthenticationService`, which finds the handler for the named or default scheme. | Call | What the cookie handler does | |---|---| | `AddAuthentication(...).AddCookie(...)` | registers the scheme, its options and the core authentication services | | `HttpContext.SignInAsync(scheme, principal, properties)` | builds a ticket, protects it, appends `Set-Cookie` | | `HttpContext.AuthenticateAsync(scheme)` | reads and unprotects the cookie, checks expiry, returns an `AuthenticateResult` | | `HttpContext.ChallengeAsync(scheme)` | sends the browser to `LoginPath` (or answers 401 on API endpoints) | | `HttpContext.SignOutAsync(scheme)` | deletes the cookie | The handler **does not authenticate credentials**. Checking a parent's email and password against your user store is your job (or ASP.NET Core Identity's, which sits on top of this handler). The cookie scheme only remembers a sign-in that already happened. ## Signing a parent in For a school's parents' portal built with Razor Pages, the login page's POST handler does four things: 1. Verify the credentials against the parent accounts. 2. Build the claims the rest of the app will read: `ClaimTypes.NameIdentifier` for the parent's id, `ClaimTypes.Name` for display, perhaps a claim per pupil the parent may see. 3. Wrap them in a `ClaimsIdentity` **whose authentication type is set**, usually to the scheme name, then in a `ClaimsPrincipal`. 4. Call `HttpContext.SignInAsync` and redirect. Step 3 is the classic trap. A `ClaimsIdentity` created without an authentication type reports `IsAuthenticated == false`, and `AuthenticationOptions.RequireAuthenticatedSignIn` (default `true`) makes `SignInAsync` throw an `InvalidOperationException` for such a principal. Inside `SignInAsync` the cookie handler: - stamps `IssuedUtc` and, unless you supplied one, `ExpiresUtc = IssuedUtc + ExpireTimeSpan` on the `AuthenticationProperties`; - raises `CookieAuthenticationEvents.OnSigningIn`, where claims can still be changed; - serializes the principal and properties into an `AuthenticationTicket` and protects it through `TicketDataFormat`, which uses Data Protection; - appends the cookie through `ChunkingCookieManager`, which splits values larger than 4050 characters into several cookies. The cookie name defaults to `.AspNetCore.` plus the scheme name, so `.AspNetCore.Cookies`. ## What happens on the next request The browser sends the cookie back. The authentication middleware asks `IAuthenticationSchemeProvider` for the **default authenticate scheme** and calls `AuthenticateAsync` on it. The cookie handler unprotects the value; a tampered or foreign cookie fails to unprotect and the result is a failure, not an exception. It then compares `ExpiresUtc` with the current time, raises `OnValidatePrincipal`, and returns success. The middleware assigns the principal to `HttpContext.User`, and from then on `User.Identity.IsAuthenticated`, `User.FindFirst(...)` and `[Authorize]` all see the parent. Two consequences are worth saying out loud in an interview: - **`SignInAsync` does not change `HttpContext.User` for the current request.** It only writes `Set-Cookie`. That is why login handlers redirect: the next request carries the cookie. - **Authentication never rejects a request by itself.** A request without the cookie simply runs with an anonymous `User`; it is authorization (`[Authorize]`, `RequireAuthorization`) that turns that into a challenge. ## Where the claims live By default the whole principal travels inside the cookie, so the server holds no session state and any instance that shares the Data Protection keys can read it. Setting `CookieAuthenticationOptions.SessionStore` to an `ITicketStore` changes that: the ticket is stored server-side and the cookie carries only a key. That keeps cookies small and makes server-side revocation possible, at the price of a store every instance must reach. ## Signing out `HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme)` makes the handler delete the cookie on the response. Without a `SessionStore` there is nothing on the server to revoke, so a copy of the cookie taken before sign-out remains valid until its ticket expires, unless `OnValidatePrincipal` rejects it. ## Mistakes an interviewer listens for - Building the principal from user input rather than from the verified account record, which lets a crafted form field become a claim. - Redirecting to a raw `returnUrl` after sign-in; use `LocalRedirect` or `Url.IsLocalUrl` so the login page cannot be turned into an open redirect. - Putting large or sensitive data in claims. The ticket is encrypted, but it is sent on every request and lives as long as the cookie. - Expecting the cookie scheme to work across several instances without shared Data Protection keys; each instance would reject the others' cookies. - Calling `SignInAsync` on a scheme that cannot sign in, such as JWT bearer; only handlers that implement sign-in (cookies among them) accept it, and the call throws otherwise.
- Right after SignInAsync, the same handler reads User.Identity.IsAuthenticated and gets false. Why?`SignInAsync` only appends the `Set-Cookie` header; it does not replace `HttpContext.User`. The authentication middleware fills `User` from the cookie on the next request, which is why a login handler redirects after signing in. If the current request genuinely needs the new identity, use the principal you just built rather than `HttpContext.User`.
- A parent signs out on a shared library computer, but a copy of the cookie taken earlier still works. Why, and what would change that?By default the ticket lives entirely in the cookie, so `SignOutAsync` can only delete the browser's copy; the server has no record to revoke. Setting `SessionStore` to an `ITicketStore` keeps the ticket server-side so sign-out can remove it, or `OnValidatePrincipal` can check a per-user security stamp and call `RejectPrincipal`.
- The portal adds a claim per pupil and some parents have many children. What happens when the ticket grows past one cookie's size?The default `ChunkingCookieManager` splits any value longer than 4050 characters into several cookies and reassembles them on read, so it keeps working, but every request now carries all the chunks. The usual fixes are fewer claims in the ticket, loading pupil links per request instead, or a `SessionStore` so the cookie carries only a key.
- AddCookie checks the parent's password and signs them in for you.
- After SignInAsync, HttpContext.User already holds the new principal in the same request.
- The auth cookie holds only a session id; the claims are kept in ISession on the server.
- new ClaimsIdentity(claims) with no authentication type is fine to pass to SignInAsync.
- Cookie authentication cannot be used without ASP.NET Core Identity underneath it.