Advertisement
Intermediate ASP.NET Core, Authorization

How do you restrict access to a minimal API endpoint or endpoint group using authorization, given minimal APIs don't use controller attributes?

Short answer

Minimal API endpoints use the fluent .RequireAuthorization() extension method (optionally passing a policy name), applicable to individual endpoints or entire route groups via MapGroup, mirroring the declarative [Authorize] attribute's behavior but in the minimal API's…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Minimal API endpoints use the fluent .RequireAuthorization() extension method (optionally passing a policy name), applicable to individual endpoints or entire route groups via MapGroup, mirroring the declarative [Authorize] attribute's behavior but in the minimal API's method-chaining style.
app.MapGet("/admin/users", () => GetUsers())
   .RequireAuthorization("AdminOnly");

// Applying to an entire group at once
var adminGroup = app.MapGroup("/admin").RequireAuthorization("AdminOnly");
adminGroup.MapGet("/users", () => GetUsers());
adminGroup.MapDelete("/users/{id}", (int id) => DeleteUser(id));
Real-world example
An admin-only minimal API route group applies RequireAuthorization once at the group level, automatically protecting every endpoint mapped within that group without repeating the authorization call on each individual route.
Likely follow-ups
  • How would you allow anonymous access to one endpoint within an otherwise-protected group?
  • Does RequireAuthorization support the same policy names as the [Authorize] attribute?
Related topics