Policy-based authorization
Policies describe access rules in one place, such as "must be an employee" or "must be over 18", and let you reuse them across the app. This lesson shows simple claim and role policies and a custom requirement with its handler.
- StartAction asks for a policy[Authorize(Policy = "AtLeast18")]
- Step 2Policy is foundRegistered in Program.cs with its requirements
- Step 3Handlers runEach requirement's handler inspects the user's claims
- Step 4Handler succeedscontext.Succeed(requirement) when the rule is met
- EndDecisionAll requirements met: allowed. Otherwise: 403
The idea in plain words
Roles answer "which group is the user in". Real rules are often richer: the user must have an EmployeeNumber claim, be older than 18, or work in a certain department. A policy is a named set of requirements. Simple ones are built with helpers like RequireClaim and RequireRole. Complex ones use a custom requirement class and a handler that contains the logic.
Because the rule lives in one place, changing it later means editing one policy rather than every controller.
Example: register policies
builder.Services.AddAuthorizationBuilder()
.AddPolicy("EmployeeOnly", p => p.RequireClaim("EmployeeNumber"))
.AddPolicy("AtLeast18", p => p.Requirements.Add(new MinimumAgeRequirement(18)));
builder.Services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();Example: requirement, handler and use
public record MinimumAgeRequirement(int Age) : IAuthorizationRequirement;
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context, MinimumAgeRequirement requirement)
{
var dob = context.User.FindFirst(ClaimTypes.DateOfBirth)?.Value;
if (dob is not null && DateTime.TryParse(dob, out var born)
&& born.AddYears(requirement.Age) <= DateTime.Today)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
[Authorize(Policy = "AtLeast18")]
public class WineController : Controller { /* ... */ }Common mistakes
- Calling context.Fail() when the rule is simply not met; just do not call Succeed, so other handlers can still succeed.
- Forgetting to register the handler, so the requirement is never satisfied.
- Putting resource-specific checks (can this user edit this document?) in attributes; use IAuthorizationService.AuthorizeAsync inside the action for resource-based authorization.
Interview question
When would you use policy-based authorization instead of roles?
Use policies when access depends on more than group membership: claims such as department or employee number, computed rules such as minimum age, combinations of conditions, or resource-based checks like whether the user owns a document. Policies centralize the rule, are testable through handlers, and can still include role requirements when needed.
Want the full details? Read the official Microsoft documentation for this topic.