Custom authorisation in ASP.NET Core: IAuthorizationRequirement, AuthorizationHandler<T> with injected services, handler lifetimes, OR semantics across handlers and Fail as a veto, IAuthorizationRequirementData attributes, failure reasons and unit testing.
A custom handler has two parts: a requirement, an immutable record implementing IAuthorizationRequirement, and a handler deriving from AuthorizationHandler<TRequirement> that calls context.Succeed(requirement) when the rule holds. Handlers are ordinary DI services, so they can inject a repository or TimeProvider; register them as IAuthorizationHandler (scoped if they use a DbContext).
Succeed is enough.Fail() is a veto that denies even if another handler succeeded, so use it only for a definite no (suspended account).IAuthorizationRequirementData lets an attribute carry the requirement.The trade-off: handlers run on every protected request, so keep them fast and cache what they look up.
"I'd split it into a requirement and a handler. The requirement is pure data: for example
ActiveSubscriptionRequirement(string Feature). It implements the empty marker interfaceIAuthorizationRequirement, and I make it a record so it's immutable. The handler derives fromAuthorizationHandler<ActiveSubscriptionRequirement>, takes its dependencies through the constructor, say anISubscriptionReaderandTimeProvider, and inHandleRequirementAsyncit reads the tenant id from the user's claims, checks the subscription and callscontext.Succeed(requirement)if it's active. If not, it just returns: not succeeding is the normal 'no'.The combination rules matter. If two handlers handle the same requirement, say one for 'has an active subscription' and one for 'is internal staff', either succeeding satisfies it. That gives me OR without touching the policy.
context.Fail()is different: it's a veto that denies the requirement even if another handler succeeded. I use it only for definite denials like a suspended tenant, and I pass anAuthorizationFailureReasonso the logs say why. For example, at [company] we [added a SuspendedTenantHandler that called Fail with a reason], and support could see 'tenant suspended' in the logs instead of a generic 403, which [cut the related tickets by about half].Handlers are registered in DI as
IAuthorizationHandler. The authorisation service resolves them from the request scope, so a scoped handler can use aDbContext. I keep them cheap because they run on every request to a protected endpoint: I cache the subscription lookup for a minute. Then I unit test the handler by building anAuthorizationHandlerContextdirectly, and integration test the endpoint withWebApplicationFactory. The senior line: a handler answers one question and returns quickly; anything slower belongs in a cache or in the token."
| Call | Meaning | Use for |
|---|---|---|
context.Succeed(req) |
This requirement is met | The rule holds |
| Return without calling anything | I can't grant it | The normal "no" |
context.Fail(reason) |
Deny, even if others succeed | Suspended account, revoked access, legal hold |
| Handler needs | Register as | Why |
|---|---|---|
| Only claims or options | Singleton | No per-request state |
DbContext or other scoped services |
Scoped | Resolved from the request scope |
| Heavy setup per call | Avoid transient | Created for every evaluation |
| Rule depends on | Approach |
|---|---|
| Claims only | RequireClaim or a small handler |
| Data about the user (subscription, tenure) | Custom handler with a cached lookup |
| A specific record (this order) | Resource-based handler via IAuthorizationService |
| Many permission names | Custom policy provider plus one generic handler |
In a [SaaS payroll] API the subscription handler first queried SQL on every request, adding [~8 ms] p95 and [~1,200] queries a minute. Caching tenant subscription state for 60 seconds in HybridCache, invalidated on plan change, brought the handler to [under 0.2 ms] and removed the queries, with no change to behaviour.
Checks that the candidate can implement a real authorisation handler, understands the evaluation semantics, and handles DI lifetimes, performance and testing.
Green flags
Fail means vetoIAuthorizationRequirementData or failure reasonsRed flags
Fail for every negative caseIAuthorizationService.AuthorizeAsync(user, resource, policy)
-> context = new AuthorizationHandlerContext(requirements, user, resource)
-> foreach handler in IAuthorizationHandlerProvider.GetHandlersAsync(context)
await handler.HandleAsync(context)
if context.HasFailed and !InvokeHandlersAfterFailure -> break
-> IAuthorizationEvaluator.Evaluate(context)
HasSucceeded = !HasFailed && PendingRequirements is empty
Every registered handler is invoked. AuthorizationHandler<T> filters context.Requirements.OfType<T>() and calls your method once per matching requirement, so a handler can ignore policies that don't contain its requirement at almost no cost.
A requirement leaves PendingRequirements the moment any handler calls Succeed. The policy succeeds when nothing is pending and nothing failed. So adding a second handler for the same requirement widens access (OR), while adding a second requirement narrows it (AND). This is the main design lever:
Policy "CanUsePayroll"
├─ ActiveSubscriptionRequirement
│ ├─ ActiveSubscriptionHandler (customer with a paid plan) } OR
│ └─ InternalStaffHandler (our support staff) }
└─ MfaRequirement AND
DefaultAuthorizationHandlerProvider receives IEnumerable<IAuthorizationHandler> from DI. The AuthorizationMiddleware resolves IPolicyEvaluator and therefore IAuthorizationService from HttpContext.RequestServices, so handlers come from the request scope. A scoped handler can depend on DbContext; a singleton handler must not capture scoped services (with ValidateScopes on in Development, the container throws).
IAuthorizationRequirementData lets an attribute return requirements directly:
[MinimumTenure(months: 12)] -> GetRequirements() => [ new MinimumTenureRequirement(12) ]
The policy provider combines these with other [Authorize] metadata, so there's no need for a custom provider that parses policy names like "MinTenure12".
context.Fail(new AuthorizationFailureReason(this, "Tenant suspended")) records why. The reasons are available on AuthorizationFailure.FailureReasons in the PolicyAuthorizationResult, which an IAuthorizationMiddlewareResultHandler can use to shape a ProblemDetails response (be careful not to leak internal detail to callers).
Handlers run on the request path. A database call per request in a handler is the same cost as one in the endpoint, but it is hidden. Cache by user or tenant with a short TTL, put stable facts in the token, and give any outbound call a timeout and a clear failure mode (deny, not hang).
InternalStaffHandler and prove OR semantics with a test.DbContext and watch ValidateScopes throw in Development.HybridCache using BenchmarkDotNet.IAuthorizationMiddlewareResultHandler that returns ProblemDetails with a safe failure code.A requirement, a handler that uses DI services, a veto handler, an attribute via IAuthorizationRequirementData, and tests.
// Authorization/Subscriptions.cs (.NET 10)
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Hybrid;
namespace Payroll.Api.Authorization;
public sealed record ActiveSubscriptionRequirement(string Feature) : IAuthorizationRequirement;
public sealed record TenantPlan(string TenantId, string[] Features, DateTimeOffset PaidUntil, bool Suspended);
public interface ISubscriptionReader
{
Task<TenantPlan?> GetAsync(string tenantId, CancellationToken ct);
}
public sealed class ActiveSubscriptionHandler(ISubscriptionReader reader, HybridCache cache, TimeProvider clock)
: AuthorizationHandler<ActiveSubscriptionRequirement>
{
protected override async Task HandleRequirementAsync(
AuthorizationHandlerContext context, ActiveSubscriptionRequirement requirement)
{
var tenantId = context.User.FindFirst("tenant_id")?.Value;
if (tenantId is null) return; // no decision: other handlers may still succeed
var plan = await cache.GetOrCreateAsync($"plan:{tenantId}",
async ct => await reader.GetAsync(tenantId, ct),
new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(1) });
if (plan is { Suspended: false } && plan.PaidUntil > clock.GetUtcNow()
&& plan.Features.Contains(requirement.Feature))
{
context.Succeed(requirement);
}
}
}
// Veto: a suspended tenant is denied even if staff or another handler would allow it.
public sealed class SuspendedTenantHandler(ISubscriptionReader reader) : IAuthorizationHandler
{
public async Task HandleAsync(AuthorizationHandlerContext context)
{
var tenantId = context.User.FindFirst("tenant_id")?.Value;
if (tenantId is null) return;
var plan = await reader.GetAsync(tenantId, CancellationToken.None);
if (plan?.Suspended == true)
context.Fail(new AuthorizationFailureReason(this, "Tenant suspended"));
}
}
// .NET 8+: the attribute carries the requirement, no custom policy provider needed.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequiresFeatureAttribute(string feature) : AuthorizeAttribute, IAuthorizationRequirementData
{
public IEnumerable<IAuthorizationRequirement> GetRequirements() => [new ActiveSubscriptionRequirement(feature)];
}
// Program.cs
builder.Services.AddHybridCache();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<ISubscriptionReader, SqlSubscriptionReader>();
builder.Services.AddScoped<IAuthorizationHandler, ActiveSubscriptionHandler>(); // scoped: reader uses DbContext
builder.Services.AddScoped<IAuthorizationHandler, SuspendedTenantHandler>();
builder.Services.AddAuthorizationBuilder()
.AddPolicy("Payslips", p => p.AddRequirements(new ActiveSubscriptionRequirement("payslips")));
app.MapGet("/payslips", () => Results.Ok()).RequireAuthorization("Payslips");
// or on a controller action: [RequiresFeature("payslips")]
// ActiveSubscriptionHandlerTests.cs (xUnit)
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using Payroll.Api.Authorization;
using Xunit;
public sealed class ActiveSubscriptionHandlerTests
{
[Fact]
public async Task Succeeds_for_paid_tenant_with_feature()
{
var clock = new FakeTimeProvider(DateTimeOffset.Parse("2026-11-20T00:00:00Z"));
var reader = Substitute.For<ISubscriptionReader>();
reader.GetAsync("t1", Arg.Any<CancellationToken>())
.Returns(new TenantPlan("t1", ["payslips"], clock.GetUtcNow().AddDays(10), false));
var cache = new ServiceCollection().AddHybridCache().Services
.BuildServiceProvider().GetRequiredService<HybridCache>();
var requirement = new ActiveSubscriptionRequirement("payslips");
var user = new ClaimsPrincipal(new ClaimsIdentity([new Claim("tenant_id", "t1")], "Test"));
var context = new AuthorizationHandlerContext([requirement], user, resource: null);
await new ActiveSubscriptionHandler(reader, cache, clock).HandleAsync(context);
Assert.True(context.HasSucceeded);
}
}
context.Fail() whenever the condition isn't met. Why it is wrong: Fail vetoes the requirement, so adding an "internal staff" handler later has no effect. Instead: return without calling Succeed (no decision from this handler); use Fail only for definite denials.DbContext as a singleton. Why it is wrong: it captures a scoped service (captive dependency), sharing one context across threads. Instead: register it as scoped, or inject IServiceScopeFactory into a singleton.HybridCache.RemoveByTagAsync) when the underlying data changes, and keep the TTL short as a backstop.context.User or context.Resource.AuthorizationHandlerContext and integration test 401/403 paths.Custom handlers are where authorisation logic should live, but they are also where hidden latency and accidental vetoes come from. I keep each handler single-purpose, decide deliberately between "no decision" and "veto", and make the expensive facts either cached or part of the token.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
RequireAssertion |
Trivial claim logic | Untestable lambdas | Needs services |
AuthorizationHandler<T> |
Reusable rule, needs DI | One class plus tests | Rule depends on a loaded resource (use resource-based) |
IAuthorizationHandler (multi-requirement) |
Veto handlers, cross-cutting checks | Must inspect pending requirements | Simple single-requirement rules |
IAuthorizationRequirementData attribute |
Parameterised requirements on endpoints | Small attribute class | Rules that change at runtime |
Measure it: add an Activity or metric around expensive handlers, watch authorisation duration in Application Insights dependency and request telemetry, and log failure reasons at Information level so support can answer "why was I denied?" without a debugger.
Authentication answers who are you? and authorisation answers what are you allowed to do? In ASP.NET Core, authentication is built from schemes: a name plus an authentication handler (cookies, JwtBearer, OpenIdConnect, or your own). The handler reads a credential from the request, validates it and produces a ClaimsPrincipal, which the authentication middleware puts on HttpContext.User. The authorisation middleware then checks the endpoint's [Authorize] metadata against that principal: no identity means a challenge (401 or a login redirect), an identity without permission means forbid (403).
Order matters: UseAuthentication must run before UseAuthorization, and both after routing and CORS, or the user is anonymous when the decision is made. The trade-off is flexibility versus clarity: several schemes are powerful, but every extra scheme is another way to be authenticated by accident.
Implement IAuthorizationMiddlewareResultHandler, wrap the default AuthorizationMiddlewareResultHandler, and when authorizeResult.Forbidden is true inspect AuthorizationFailure.FailureReasons. Map each known reason to a stable ProblemDetails: Status = 403, a documented type URI (for example https://errors.example.com.au/tenant-suspended), a short title ("Subscription suspended") and a user-friendly detail that tells the user what to do, plus the traceId. Write it with IProblemDetailsService so it matches your other errors. Log the full reason server-side (requirement, policy, user and tenant ids) and keep the client message coarse, so you help legitimate users without telling an attacker which rule to get around. Unknown reasons get a generic 403 problem; 401 challenges stay on the default path so cookie redirects and WWW-Authenticate headers still work.
How to tell it (STAR)
**S:** In our [payroll SaaS], a tenant suspended for non-payment could still run pay runs through accounts that had a support flag. **T:** I was asked to find out why and make suspension reliable. **A:** I replayed the requests with authorisation debug logging and found two handlers satisfying the same requirement, so the staff handler's success made the subscription check irrelevant. I added a veto handler that calls `Fail` with a reason for suspended tenants, mapped the reason to a clear problem response, invalidated the cached plan on suspension and wrote tests for every handler combination. **R:** Suspension took effect within [60 seconds] for all [~600] tenants, support could see the denial reason in logs, and the same pattern caught [one more] missing veto in [the reporting module].
Last updated 23 Nov 2026.