Authentication verifies the identity of a user, service, or other principal before an API grants access. In a production web service, it addresses the risk that anyone could call protected endpoints and perform unrestricted actions. section 9.0 section 9.5
A practical design delegates account management to an external identity provider through OpenID Connect. The API receives authentication information, commonly as a JSON Web Token (JWT), and verifies the token presented with the request. ASP.NET Core Identity supplies the authentication and authorization integration without requiring the API to manage user accounts directly. section 9.5
A token-based ASP.NET Core setup follows this request pipeline:
- Register JWT bearer authentication and select JwtBearerDefaults.AuthenticationScheme. section 9.5
- Enable authentication middleware before authorization middleware. section 9.5
- Mark a controller with [Authorize] so unauthenticated callers cannot access it. section 9.5
Listing 9.15 Adding authentication and authorization
using Microsoft.AspNetCore.Authentication.JwtBearer; #1
builder.Services
.AddAuthentication(
JwtBearerDefaults.AuthenticationScheme) #2
.AddJwtBearer(); #3
var app = builder.Build(); #4
app.UseAuthentication(); #5
app.UseAuthorization(); #6
Inspect the focused ASP.NET Core configuration that registers JWT bearer authentication and places authentication before authorization. section 9.5
Listing 9.16 Turning on authorization for the CatalogController
[ApiController]
[Route("[controller]")]
[Authorize] #1
public class CatalogController : ControllerBase
{ /*...*/ }
Inspect the controller-level authorization marker that restricts the CatalogController to authenticated requests. section 9.5

































