RequireAuthorization applies an authorization requirement to an ASP.NET Core minimal API endpoint or route group. With no arguments, it requires an authenticated request; unauthorized requests are rejected before the endpoint runs. section 25.3 section 25.6
Protecting a minimal API endpoint
app.MapGet("/recipe", async (RecipeService service) => { return await service.GetRecipes(); }).RequireAuthorization(); The application must register authentication and authorization services and make their middleware available. A request without a valid bearer token receives a 401 Unauthorized response. section 25.3
Choose the form that matches the endpoint’s access rule:
- Use RequireAuthorization() for the default authenticated-user requirement. section 25.6
- Pass a policy name, such as RequireAuthorization("CanCreate"), to apply a specific authorization policy. section 25.6
- Use AllowAnonymous() when an endpoint must bypass authentication requirements. section 25.6
- Use IAuthorizationService for resource-based decisions, such as allowing users to delete only recipes they created. section 25.6
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
Shows the complete minimal API arrangement: JWT bearer authentication, authorization services, middleware, and RequireAuthorization on an endpoint. section 25.3
