In ASP.NET Core, how do you build a policy from a custom requirement and an AuthorizationHandler<T>, and how are several handlers' results combined?
answer
- IAuthorizationRequirement is a marker
- AddAuthorizationBuilder().AddPolicy(...)
- HandleRequirementAsync: Succeed or stay silent
- Fail() vetoes every other handler
- InvokeHandlersAfterFailure defaults to true
basics
~10 sA policy lists requirements (IAuthorizationRequirement); handlers deriving from AuthorizationHandler<TRequirement> call context.Succeed(requirement) when it is met. Every requirement must succeed, any one handler can satisfy a requirement, and a single context.Fail() fails the whole evaluation.
solid answer
~40 sA **requirement** is a class implementing the empty marker `IAuthorizationRequirement`, holding whatever data the rule needs. A **policy** is registered with `builder.Services.AddAuthorizationBuilder().AddPolicy("ContractSigner", p => p.AddRequirements(new SigningLimitRequirement(50_000)))`. A **handler** derives from `AuthorizationHandler<SigningLimitRequirement>`, overrides `HandleRequirementAsync` and calls `context.Succeed(requirement)` when the user qualifies; register it as an `IAuthorizationHandler` in DI. Results combine like this: **all requirements** of the policy must be marked succeeded; **any one handler** calling `Succeed` satisfies a requirement; a handler that does nothing is neutral; and any handler calling `context.Fail()` fails the evaluation even if others succeeded. `InvokeHandlersAfterFailure` (default `true`) keeps running the remaining handlers after a failure, for logging or side effects.
code
csharp · 16 linespublic sealed record SigningLimitRequirement(decimal Amount) : IAuthorizationRequirement;
public sealed class SigningLimitHandler : AuthorizationHandler<SigningLimitRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context, SigningLimitRequirement requirement)
{
var claim = context.User.FindFirst("signing_limit")?.Value;
if (decimal.TryParse(claim, CultureInfo.InvariantCulture, out var limit)
&& limit >= requirement.Amount)
{
context.Succeed(requirement);
}
return Task.CompletedTask; // silent = neutral, not a veto
}
}go deeper
Recall the three pieces: a requirement class, a handler that calls context.Succeed, and AddPolicy to give the pair a name used by [Authorize].
Explain the combination rules: requirements are ANDed, handlers for one requirement are ORed, silence is neutral and Fail() is a veto; register handlers as IAuthorizationHandler.
Choose handler lifetimes deliberately, use Fail only for hard denials, and know that a missing registration silently denies everything behind the policy.
Weigh where policy logic should live as rules multiply: named policies and handlers kept testable and reviewable, rather than role strings scattered across attributes.
## The three moving parts ASP.NET Core's policy-based authorization separates **what** must be true from **how** it is checked: - A **requirement** implements `IAuthorizationRequirement`, an interface with no members. It is a data holder: a minimum signing limit, a department name, an operation. - A **policy** (`AuthorizationPolicy`) is a named list of requirements plus optional authentication schemes, built with `AuthorizationPolicyBuilder`. - A **handler** implements `IAuthorizationHandler`. Most derive from `AuthorizationHandler<TRequirement>`, whose `HandleAsync` loops over the policy's requirements of type `TRequirement` and calls your `HandleRequirementAsync(context, requirement)` for each one. The built-in builder methods are just shortcuts that add built-in requirements: `RequireAuthenticatedUser()` adds `DenyAnonymousAuthorizationRequirement`, `RequireRole(...)` adds `RolesAuthorizationRequirement`, `RequireClaim(...)` adds `ClaimsAuthorizationRequirement`, and `RequireAssertion(ctx => ...)` wraps a lambda in an `AssertionRequirement`. ## Registering the policy and the handler `AddAuthorizationBuilder()` registers the authorization services and returns an `AuthorizationBuilder` with a fluent API: `AddPolicy`, `AddDefaultPolicy`, `AddFallbackPolicy`, `SetDefaultPolicy`, `SetFallbackPolicy` and `SetInvokeHandlersAfterFailure`. The older `AddAuthorization(options => options.AddPolicy(...))` form configures the same `AuthorizationOptions`. Handlers are **not** discovered by scanning. You register each one as `IAuthorizationHandler`, and the default handler provider receives every registration through `IEnumerable<IAuthorizationHandler>`. Any lifetime works, and the choice matters: - `AddSingleton` is fine for a handler that only reads claims. - A handler that needs a scoped dependency, such as a `DbContext`, must be registered `AddScoped`; a singleton would capture the scoped service. A requirement can also implement `IAuthorizationHandler` itself. The always-registered `PassThroughAuthorizationHandler` calls such self-handling requirements, so a simple rule needs only one class. ## How results combine After all handlers run, the evaluator looks at the `AuthorizationHandlerContext`: | Situation | Outcome | |---|---| | Every requirement was marked by some handler's `Succeed`, and nobody called `Fail` | Success | | A requirement is still in `PendingRequirements` | Failure (the pending requirements are reported) | | Any handler called `Fail()` or `Fail(reason)` | Failure, even if every requirement succeeded | Read as logic: 1. Requirements within a policy are **AND**ed. 2. Handlers for the same requirement are **OR**ed: one `Succeed` is enough. 3. Doing nothing is **neutral**, which is what a handler should do when the rule simply does not apply to this user. 4. `Fail()` is a **veto**. Reserve it for "this must be denied whatever else says", such as a suspended account. `AuthorizationOptions.InvokeHandlersAfterFailure` defaults to `true`, so the remaining handlers still run after a `Fail`. Setting it to `false` stops at the first failure, which saves work but skips any handler that logs or audits. ## Saying why access was denied A failed evaluation returns an `AuthorizationResult` whose `Failure` property describes it: - `FailedRequirements` lists the requirements nobody satisfied; - `FailCalled` is true when some handler vetoed; - `FailureReasons` carries the `AuthorizationFailureReason` objects handlers passed to `context.Fail(reason)`, each naming the handler and a message. Those details are for logs and for a custom `IAuthorizationMiddlewareResultHandler`, for example to return a specific problem body when a delegation has expired. They should not be echoed to the client verbatim, because they describe your rules to whoever is probing them. ## Roles, claims or a handler? The right tool depends on the rule: - **Role membership** that the identity already carries: `RequireRole("Manager")` or `[Authorize(Roles = "Manager")]`. Inside one `RequireRole` call the roles are alternatives. - **A claim with an allowed value**: `RequireClaim("department", "Legal", "Procurement")`, which compares the values ordinally. - **A small inline rule**: `RequireAssertion(ctx => ...)`. - **Anything that needs data, services or tests**: a requirement plus an `AuthorizationHandler<T>`. ## Worked example: signing limits In a contract-management system, only users whose `signing_limit` claim covers a threshold may sign. `SigningLimitRequirement(50_000)` carries the threshold; `SigningLimitHandler` parses the claim and calls `Succeed` when it is high enough, and otherwise stays silent. A second handler for the same requirement, `GeneralCounselHandler`, succeeds for anyone in the `GeneralCounsel` role. Either handler can grant access, and neither blocks the other. ## Traps - Calling `Fail()` when a rule merely does not apply turns an OR into an AND and locks out users another handler would have admitted. - A handler that is never registered never runs, so the requirement stays pending and every request is denied, with no exception to point at it. - A handler deriving from `AuthorizationHandler<TRequirement, TResource>` runs only when the `Resource` passed in is a `TResource`; behind an attribute, that resource is the `HttpContext`.
- Your handler needs a DbContext to look up a user's delegations. How do you register it?Register it with `AddScoped<IAuthorizationHandler, DelegationHandler>()`. The authorization service and handler provider are transient and resolved from the request's services, so a scoped handler gets the request's `DbContext`. Registering it as a singleton would capture a scoped `DbContext`, which scope validation rejects in Development.
- When should a handler call context.Fail() instead of simply not calling Succeed?Only when the request must be denied whatever other handlers decide, such as a suspended account or a revoked delegation. Not calling `Succeed` leaves the decision to other handlers; `Fail()` vetoes them all, so using it for "this rule doesn't apply" locks out users another handler would admit.
- What does setting InvokeHandlersAfterFailure to false change?The authorization service stops running handlers as soon as the context has failed, instead of running all of them. The outcome is the same failure; what you lose is any work later handlers did, such as audit logging or attaching extra `AuthorizationFailureReason` entries.
- Every handler registered for a requirement must call Succeed for it to pass.
- A handler should call context.Fail() whenever its own rule is not met.
- Handlers are discovered automatically from the assembly without registration.
- InvokeHandlersAfterFailure defaults to false, so handlers stop at the first failure.
- IAuthorizationRequirement has an Evaluate method each requirement must implement.