In an ASP.NET Core contract-management API, how do you let only a document's owner or a manager edit it, when [Authorize] runs before the document is loaded?
answer
- imperative, not declarative
- IAuthorizationService.AuthorizeAsync(user, resource, ...)
- AuthorizationHandler<TRequirement, TResource>
- OperationAuthorizationRequirement for verbs
- AuthorizationResult.Succeeded, then Forbid or Challenge
basics
~10 sLoad the document first, then call IAuthorizationService.AuthorizeAsync(User, document, policyOrRequirement). Handlers deriving from AuthorizationHandler<TRequirement, Document> receive the document: one succeeds for its owner, another for managers. On failure, return Forbid() for a signed-in user.
solid answer
~40 sAttribute authorization is evaluated before model binding and before the action loads anything, so it cannot see the document. Use **imperative** authorization: inject `IAuthorizationService`, load the document, then call `AuthorizeAsync(User, document, "EditDocument")` (or pass a requirement such as an `OperationAuthorizationRequirement` named `Edit`). Write handlers deriving from `AuthorizationHandler<TRequirement, ContractDocument>`; the framework calls them only when the resource is a `ContractDocument`. One handler calls `Succeed` when the user's id matches `document.OwnerId`, another when the user is in the `Manager` role. Because handlers for one requirement are alternatives, either grants access. Check `AuthorizationResult.Succeeded`, and on failure return `Forbid()` for an authenticated user and `Challenge()` otherwise. Keep `[Authorize]` on the endpoint as well, so anonymous callers are rejected before any database work happens.
code
csharp · 24 linespublic sealed class EditDocumentRequirement : IAuthorizationRequirement;
public sealed class DocumentOwnerHandler
: AuthorizationHandler<EditDocumentRequirement, ContractDocument>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
EditDocumentRequirement requirement, ContractDocument document)
{
if (context.User.FindFirstValue(ClaimTypes.NameIdentifier) == document.OwnerId)
context.Succeed(requirement);
return Task.CompletedTask;
}
}
public sealed class ManagerHandler
: AuthorizationHandler<EditDocumentRequirement, ContractDocument>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
EditDocumentRequirement requirement, ContractDocument document)
{
if (context.User.IsInRole("Manager")) context.Succeed(requirement);
return Task.CompletedTask;
}
}go deeper
Recall that ownership checks need the loaded record, so they happen in code through IAuthorizationService rather than in an attribute.
Explain AuthorizationHandler<TRequirement, TResource>, why two handlers express owner-or-manager, and how to turn AuthorizationResult into Forbid or Challenge.
Spot the failure modes: a mismatched TResource silently denying, an ignored result authorizing everyone, 403 leaking existence, and lists needing a query filter instead.
Decide where per-record rules live across services so they are not duplicated: shared handlers, query filters for lists, and one consistent answer for forbidden versus missing.
## Why an attribute cannot do this The authorization middleware runs after routing selects an endpoint and **before** the endpoint executes. At that point no route value has been bound to a parameter and no document has been loaded. Behind an attribute, the only resource a handler receives in `AuthorizationHandlerContext.Resource` is the `HttpContext`, so a rule that depends on a property of a stored record (its owner, its status, its department) cannot be expressed declaratively. ASP.NET Core calls the alternative **imperative authorization**: the code that loads the resource asks the authorization service about it. ## The pieces - **`IAuthorizationService`**, registered by `AddAuthorization`, injected into the controller or the Minimal API handler. Its core method is `AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName)`, and extension methods accept a single `IAuthorizationRequirement` or an `AuthorizationPolicy`. It returns `Task<AuthorizationResult>`. - **`AuthorizationHandler<TRequirement, TResource>`**, whose `HandleAsync` checks `context.Resource is TResource` and only then calls `HandleRequirementAsync(context, requirement, resource)`. - **A requirement** to name what is being asked. Either your own marker class, or the built-in `OperationAuthorizationRequirement`, which has just a `Name` such as `"Edit"` or `"Delete"`, so one handler can answer several verbs. ## Owner or manager, as handlers The rule "owner **or** manager" maps directly onto the combination rules: requirements are ANDed, and **handlers for the same requirement are ORed**. So: 1. `DocumentOwnerHandler : AuthorizationHandler<EditDocumentRequirement, ContractDocument>` calls `context.Succeed(requirement)` when the user's `NameIdentifier` claim equals `document.OwnerId`. 2. `ManagerHandler : AuthorizationHandler<EditDocumentRequirement, ContractDocument>` calls `Succeed` when `context.User.IsInRole("Manager")`. 3. Neither calls `Fail()` when its rule does not match. Silence is neutral, and calling `Fail` would let the owner handler veto every manager. Register both as `IAuthorizationHandler` and register the policy with `AddAuthorizationBuilder().AddPolicy("EditDocument", p => p.AddRequirements(new EditDocumentRequirement()))`. ## Calling it from the endpoint The endpoint keeps `[Authorize]` (or `.RequireAuthorization()`) so that anonymous callers are challenged before any query runs. Inside the endpoint: 1. Load the document; return `404` if it does not exist. 2. `var result = await authz.AuthorizeAsync(User, document, "EditDocument");` 3. If `result.Succeeded` is false, return `Forbid()` (or `Results.Forbid()`), because the user is already authenticated. 4. Otherwise perform the edit. `result.Failure` explains the denial: `FailCalled`, `FailedRequirements` and `FailureReasons` are useful in logs but should not be echoed to the client. ## Comparing the options | Approach | Sees the document? | Where it lives | Fits | |---|---|---|---| | `[Authorize(Policy = ...)]` | No; the resource is the `HttpContext` | Endpoint metadata | Rules about the user alone | | `IAuthorizationService.AuthorizeAsync(User, doc, ...)` | Yes | Inside the endpoint, after loading | Ownership, status and per-record rules | | A query filter (`WHERE OwnerId = @me`) | Implicitly | Data access | Lists, where loading then rejecting each row is wasteful | Lists are the case where imperative checks scale badly: loading 500 contracts and authorizing each one is slower than filtering in the query, and a filtered query never loads the rows the user may not see. Many APIs therefore use **both**: a filtered query for lists, and `AuthorizeAsync` for single-document reads and writes. ## Testing the handlers Resource handlers are plain classes, so they are tested without a web host: 1. Build a `ClaimsPrincipal` with the `NameIdentifier` or role claims under test. 2. Create `new AuthorizationHandlerContext(new[] { requirement }, user, document)`; its constructor takes the requirements, the user and the resource. 3. Call `await handler.HandleAsync(context)`. 4. Assert `context.HasSucceeded` for the owner and the manager, and assert it is false for a third user. Testing the two handlers separately, and then through `IAuthorizationService` with both registered, proves both the individual rules and the OR between them. ## Pitfalls - **Wrong `TResource`.** A handler typed for `ContractDocument` does nothing when called with a DTO or an id, so the requirement stays pending and access is always denied, with no exception. - **Ignoring the result.** `AuthorizeAsync` returns a result and throws nothing on denial; code that awaits it and carries on has authorized everyone. - **Leaking existence.** Returning `403` for a document the user may not see confirms that it exists. When that matters, return `404` for both missing and forbidden documents. - **Policy names applied as attributes.** Putting `[Authorize(Policy = "EditDocument")]` on the endpoint as well runs the same requirement with the `HttpContext` as resource, where no handler succeeds, so every call is denied.
- Why use OperationAuthorizationRequirement instead of one requirement class per verb?`OperationAuthorizationRequirement` carries only a `Name`, so a single `AuthorizationHandler<OperationAuthorizationRequirement, ContractDocument>` can switch on `Read`, `Edit` and `Delete` and apply one ownership model to all of them. You pass the requirement directly: `AuthorizeAsync(user, document, new OperationAuthorizationRequirement { Name = "Edit" })`.
- A resource handler never seems to run. What do you check first?That the object passed as `resource` is exactly the handler's `TResource` (or derives from it): a DTO, an id or the `HttpContext` makes `HandleAsync` skip it. Then check that the handler is registered as `IAuthorizationHandler` and that the requirement type in the policy matches the handler's `TRequirement`.
- Putting [Authorize(Policy = "EditDocument")] on the action is enough to check ownership.
- AuthorizeAsync throws an exception when authorization fails.
- The owner handler should call context.Fail() when the user is not the owner.
- Challenge() is the right response when a signed-in user who is not the owner is denied.
- Resource-based checks are the right way to filter a list of 500 documents.