liveBook · Manning

UseAuthentication

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

UseAuthentication is an ASP.NET Core extension method that adds authentication middleware at a specified point in the request pipeline.

UseAuthentication adds authentication middleware at a chosen point in the ASP.NET Core request pipeline. The middleware establishes the current principal when a user logs in and can load it from an authentication cookie on later requests. section 23.7

Place authentication where later middleware can use the authenticated request:

  • Call UseAuthentication before middleware that requires an authenticated user, especially UseAuthorization. section 23.7
  • When controlling the pipeline explicitly, keep UseRouting, UseAuthentication, UseAuthorization, and UseEndpoints in that overall order. section 24.2
  • WebApplication adds AuthenticationMiddleware automatically, but UseAuthentication lets you ensure its position explicitly. section 23.7

Explicit middleware order

A pipeline that makes the dependency visible can be written as: app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(...). Authentication populates HttpContext.User before authorization evaluates whether the selected endpoint may execute. section 24.2 section 23.7

Figure 24.2 Authorization occurs after an endpoint has been selected and after the request is authenticated, but before the action method or Razor Page endpoint is executed.
CH24_F02_Lock3

The pipeline figure clarifies that authentication happens after endpoint selection and before authorization and endpoint execution. section 24.2

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

How deep it goes
Explains middleware behavior and ordering, but defers authentication-provider configuration and user-interface implementation.
Examples
Uses an explicitly ordered middleware pipeline and a figure showing authentication before authorization and endpoint execution.
What it assumes
Assumes familiarity with ASP.NET Core middleware and endpoints while treating authentication, principals, cookies, and authorization ordering as teachable concepts.
What you can do after
Operate/configure an ASP.NET Core pipeline so authentication runs before authorization and other dependent middleware.
How it connects
Connects authentication middleware with UseRouting, UseAuthorization, HttpContext.User, claims, cookies, and ASP.NET Core Identity.

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.