In this lesson, you will learn how to transition your established authorization policies into the streamlined, route-centric world of Minimal APIs.
While MVC relies heavily on controllers and attributes, Minimal APIs use the RequireAuthorization() extension method directly on your route handlers. This keeps your security logic tightly coupled with the endpoint definition, making it easier to see exactly who can access what at a glance.
Applying Policies to Minimal APIs
The core idea is to treat your authorization policies as metadata for your routes. You define your policies in the Program.cs service configuration as usual, then apply them to specific endpoints using the .RequireAuthorization() method.
Consider this example where we secure an endpoint using a specific policy:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});
var app = builder.Build();
// Secure a specific route with the 'AdminOnly' policy
app.MapGet("/admin/reports", () => "Sensitive Data")
.RequireAuthorization("AdminOnly");
app.Run();
Why This Matters for Minimal APIs
Because Minimal APIs lack the filter pipeline of traditional controllers, RequireAuthorization() acts as the primary gatekeeper. You can chain these methods to enforce granular security. For instance, if you need multiple policies or want to allow anonymous access to specific routes while locking down others, you can use .AllowAnonymous() or stack authorizations.
This paradigm is particularly powerful because the security requirement is declared exactly where the route is defined. This reduces "configuration drift," where a developer might update a controller but forget to update a global security policy. By keeping your security declarations explicitly attached to the Map methods, you ensure that the intent of the endpoint matches the protection applied to it.
As you build out your microservices or lightweight API endpoints, remember that every Map method is an opportunity to apply a specific policy, allowing you to build a security layer that is as modular as the API itself.
Key Takeaway: Use the RequireAuthorization() method on Minimal API route handlers to apply specific authorization policies directly to your endpoints, ensuring security is as modular and explicit as your code.