liveBook · Manning

AuthenticationMiddleware

As explained in ASP.NET Core in Action, 3e

AuthenticationMiddleware is ASP.NET Core middleware that authenticates the user associated with an HTTP request.

AuthenticationMiddleware authenticates an incoming HTTP request and establishes its current user. When a browser sends an authentication cookie, authentication services validate and deserialize it into a ClaimsPrincipal, which is assigned to HttpContext.User. section 23.1.2

The request pipeline behaves as follows:

  • Kestrel initially assigns an anonymous principal to HttpContext.User. section 23.1.2
  • AuthenticationMiddleware calls the authentication services to read, decrypt, and deserialize the authentication cookie. section 23.1.2
  • The middleware replaces the anonymous principal with the authenticated ClaimsPrincipal, allowing later middleware and application code to use the current user. section 23.1.2
  • Place authentication before middleware that needs an authenticated user, especially authorization middleware; UseAuthentication() makes the position explicit. section 23.7

A subsequent request after sign-in

A user signs in once, and the principal is serialized into an authentication cookie. On a later request, the browser sends that cookie automatically. AuthenticationMiddleware restores the principal and makes the user available through HttpContext.User. Later code can display the user’s name or restrict access based on claims. section 23.1.2

Figure 23.3 A subsequent request after signing in to an application. The cookie sent with the request contains the user principal, which is validated and used to authenticate the request.
CH23_F03_Lock3

Follow the request flow from the authentication cookie to validation and the authenticated user principal. section 23.1.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains cookie reading, decryption, deserialization, principal assignment, and pipeline ordering, while stopping short of authorization decisions.
Examples
Uses a signed-in browser’s subsequent cookie-bearing request to show principal validation and restoration.
What it assumes
Assumes HTTP requests, cookies, and sign-in exist, while explaining how ASP.NET Core restores the user principal from a cookie.
What you can do after
Diagnose authentication failures by checking whether AuthenticationMiddleware runs before code that requires an authenticated user.
How it connects
Connects authentication services, authentication cookies, ClaimsPrincipal, HttpContext.User, claims, and authorization middleware.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.