Microsoft.AspNetCore.Authentication.JwtBearer adds JWT bearer authentication to ASP.NET Core APIs. The middleware reads and validates bearer tokens, then creates a ClaimsPrincipal for the request. section 25.3 section 25.7
Configure a protected API in a few focused steps:
- Install the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package. section 25.3
- Call AddAuthentication().AddJwtBearer() and AddAuthorization() to register the services. section 25.3
- Use authentication and authorization middleware, then protect endpoints with RequireAuthorization() or [Authorize]. section 25.3
Protecting a recipe endpoint
A minimal API can expose /recipe and require authentication. A request without a valid bearer token receives a 401 Unauthorized challenge; a valid token supplies the authenticated user to the request. section 25.3 section 25.7
Listing 25.1 Adding JWT bearer authentication to a minimal API application
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication() #1 .AddJwtBearer(); #2 builder.Services.AddAuthorization(); #3 builder.Services.AddScoped<RecipeService>(); WebApplication app = builder.Build(); app.UseAuthentication(); #4 app.UseAuthorization(); #5 app.MapGet("/recipe", async (RecipeService service) => { return await service.GetRecipes(); }).RequireAuthorization(); #6 app.Run(); #1 Adds the core authentication services #2 Adds and configures JWT authentication #3 Adds the core authorization services #4 Adds the authentication middleware #5 Adds the authorization middleware #6 Adds an authorization policy to the minimal API endpoint
Use the complete minimal API listing to see service registration, middleware ordering, and endpoint protection together. section 25.3
