ASP.NET Core Interview Question #136
How do custom authorization requirements and handlers work?
Authentication, Authorization & Security Mid-Level Intermediate
Quick Interview Answer
A custom authorization requirement represents an access condition that cannot be expressed cleanly with built-in role or claim requirements. A handler evaluates the requirement against the current authorization context and calls Succeed when the condition is met.
Detailed Explanation
A custom authorization requirement represents an access condition that cannot be expressed cleanly with built-in role or claim requirements. A handler evaluates the requirement against the current authorization context and calls Succeed when the condition is met.
This approach keeps reusable authorization logic outside controllers and supports dependency injection in handlers. A policy can contain multiple requirements, all of which normally need to succeed.
Code Example
public sealed class MinimumAccountAgeRequirement : IAuthorizationRequirement
{
public int Days { get; }
public MinimumAccountAgeRequirement(int days) => Days = days;
}
public sealed class MinimumAccountAgeHandler
: AuthorizationHandler<MinimumAccountAgeRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
MinimumAccountAgeRequirement requirement)
{
// Evaluate trusted user data here.
// context.Succeed(requirement) when satisfied.
return Task.CompletedTask;
}
}