How would you implement a custom IAuthorizationRequirement and IAuthorizationHandler for a business rule like 'only during business hours'?
Short answer
Define a class implementing IAuthorizationRequirement (often just a marker with no logic itself), then an AuthorizationHandler subclass implementing HandleRequirementAsync that evaluates the actual business rule (checking DateTime.Now against configured business hours) and calls…
Advertisement
AModel answer
Define a class implementing IAuthorizationRequirement (often just a marker with no logic itself), then an AuthorizationHandler<TRequirement> subclass implementing HandleRequirementAsync that evaluates the actual business rule (checking DateTime.Now against configured business hours) and calls context.Succeed(requirement) if satisfied -- registered via services.AddScoped<IAuthorizationHandler, BusinessHoursHandler>() and referenced in a policy.
public class BusinessHoursRequirement : IAuthorizationRequirement { }
public class BusinessHoursHandler : AuthorizationHandler<BusinessHoursRequirement> {
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, BusinessHoursRequirement requirement) {
var now = DateTime.Now.TimeOfDay;
if (now >= TimeSpan.FromHours(9) && now <= TimeSpan.FromHours(17))
context.Succeed(requirement);
return Task.CompletedTask;
}
}
builder.Services.AddAuthorization(o => o.AddPolicy("BusinessHoursOnly", p => p.Requirements.Add(new BusinessHoursRequirement())));Real-world example
A high-risk financial transaction endpoint restricts execution to business hours using a custom requirement/handler pair, ensuring transfers above a threshold can only be initiated when support staff are available to respond to issues.
Likely follow-ups
- How would you inject additional dependencies (like a holiday calendar service) into the handler?
- What happens if a policy has requirements that can never succeed due to a bug?
Related topics