Resource-based authorisation: why endpoint policies can't see the record, AuthorizationHandler<TRequirement, TResource>, OperationAuthorizationRequirement, calling IAuthorizationService.AuthorizeAsync after loading, 403 vs 404, and filtering lists in the query.
Resource-based authorisation decides using the record itself: its owner, team, tenant or state (a paid invoice can't be edited). An endpoint policy can't do it alone because the authorisation middleware runs before your code loads the record.
AuthorizationHandler<TRequirement, TResource>, usually with OperationAuthorizationRequirement (Read, Update, Delete) so one handler holds every rule for a resource type: owner, team editor, viewer, admin.IAuthorizationService.AuthorizeAsync(User, document, Operations.Update), and return Forbid(), or NotFound() when even confirming the record exists would disclose information.The trade-off: it's imperative, so a developer can forget the call. Back it with tests and query filters.
"Policies on the endpoint answer questions about the user: are they signed in, do they have the editor role or the
documents.writescope. 'Is this user the owner of document 42' is a question about the data, and the authorisation middleware runs before my endpoint has loaded document 42. So ASP.NET Core gives us resource-based authorisation: I write a handler that derives fromAuthorizationHandler<OperationAuthorizationRequirement, Document>, and in the endpoint I load the document, then callIAuthorizationService.AuthorizeAsync(User, document, Operations.Update). If it fails I returnForbid(), orNotFound()if even knowing the document exists would leak something, which is usually the case for customer data.I like
OperationAuthorizationRequirementbecause one handler per resource type holds all the rules: owners can read, update and delete; editors in the same team can read and update; admins can read. The rules live in one testable class instead ofifstatements spread through endpoints. For example, at [company] we had ownership checks copied into [about 30] endpoints with slightly different logic, and one of them [compared the wrong id]. Moving them into aDocumentAuthorizationHandlerwith a table-driven unit test [found two more inconsistencies] and made the pen-test retest clean.The mistake I see is doing it for single records but forgetting lists. For
GET /documents, I don't load everything and authorise each item; I filter in the query by owner or team, usually via an EF Core global query filter for the tenant plus an explicitWherefor ownership. The senior line: the endpoint policy is the front door, resource-based authorisation is the lock on each room, and you need both."
| Question | Mechanism | Runs |
|---|---|---|
| Is the caller signed in, with the right scope? | Endpoint policy | Middleware, before the endpoint |
| May this caller update document 42? | AuthorizeAsync(User, doc, Update) |
In the endpoint, after loading |
| Which documents may this caller list? | Query filter / Where |
In the database |
| May they change this field? | Input DTO without the field, or a field-level check | Binding and handler |
| Return | When |
|---|---|
| 403 Forbidden | The caller can already see the resource exists (shared team space) |
| 404 Not Found | Existence is sensitive: other customers' records, enumerable ids |
After consolidating ownership checks into one handler for the [document management] API, [31] endpoints went through the same rules, the handler's unit tests covered [18] user/operation combinations in [under a second], and a cross-user integration test suite caught [one] new endpoint that skipped the check before it reached production.
Checks that the candidate knows why endpoint policies can't protect individual records and can implement resource-based authorisation correctly, including lists.
Green flags
AuthorizationHandler<TRequirement, TResource> and IAuthorizationServiceRed flags
UseAuthorization -> evaluates endpoint policies resource = HttpContext (no document yet)
endpoint -> db.Documents.FindAsync(id) now we have the document
-> AuthorizeAsync(User, doc, op) resource = Document
You could read the route id in a handler and load the record there, but then the record is loaded twice and the handler is tied to HTTP. Resource-based authorisation keeps the decision in a handler but lets the endpoint supply the resource.
AuthorizationHandler<TRequirement, TResource> only runs when context.Resource is a TResource. Combined with OperationAuthorizationRequirement { Name = "Update" }, one handler serves every operation on a type:
DocumentAuthorizationHandler : AuthorizationHandler<OperationAuthorizationRequirement, Document>
Read -> owner | same team | admin
Update -> owner | (same team and editor)
Delete -> owner
You can also define a requirement per rule (SameTeamRequirement) and use named policies with AuthorizeAsync(User, doc, "SameTeam"); the operation style scales better when a type has several operations.
Authorising after loading a list is slow (you load rows the user can't see), breaks paging (page 1 has 3 items instead of 20), and leaks counts. Push the rule into SQL:
db.Documents
.Where(d => d.OwnerId == userId || d.Team.Members.Any(m => m.UserId == userId))
.OrderBy(d => d.Id).Take(20)
For multi-tenant data an EF Core global query filter on TenantId is the safety net, and SQL Server row-level security is a defence in depth beneath it.
The weakness of imperative checks is that someone forgets them. Mitigations:
GetForUpdateAsync(id, user)), so endpoints never load an entity without a check.{id} route value.Resource handlers can also check state: an invoice can't be updated once it is Paid. Keep business invariants in the domain (the entity rejects the change) and access rules in the handler; don't mix them.
WebApplicationFactory test where user B requests user A's document and asserts 404.ToListAsync, with 10,000 rows.TenantId and confirm it applies to Included navigations.One handler per resource type using OperationAuthorizationRequirement, called after loading the document.
// Documents/DocumentAuthorization.cs (.NET 10)
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
namespace Docs.Api.Documents;
public sealed class Document
{
public int Id { get; init; }
public required string OwnerId { get; init; }
public required string TeamId { get; init; }
public required string Title { get; set; }
}
public static class Operations
{
public static readonly OperationAuthorizationRequirement Read = new() { Name = nameof(Read) };
public static readonly OperationAuthorizationRequirement Update = new() { Name = nameof(Update) };
public static readonly OperationAuthorizationRequirement Delete = new() { Name = nameof(Delete) };
}
public sealed class DocumentAuthorizationHandler
: AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
OperationAuthorizationRequirement requirement, Document doc)
{
var userId = context.User.FindFirstValue("sub");
var isOwner = userId is not null && userId == doc.OwnerId;
var sameTeam = context.User.HasClaim("team_id", doc.TeamId);
var isEditor = context.User.IsInRole("Editor");
var allowed = requirement.Name switch
{
nameof(Operations.Read) => isOwner || sameTeam,
nameof(Operations.Update) => isOwner || (sameTeam && isEditor),
nameof(Operations.Delete) => isOwner,
_ => false
};
if (allowed) context.Succeed(requirement);
return Task.CompletedTask;
}
}
// Program.cs
builder.Services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>(); // claims only: singleton is fine
var docs = app.MapGroup("/documents").RequireAuthorization(); // front door: signed in
docs.MapPut("/{id:int}", async (int id, UpdateDocument body, ClaimsPrincipal user,
DocsDb db, IAuthorizationService authz, CancellationToken ct) =>
{
var doc = await db.Documents.FindAsync([id], ct);
if (doc is null) return Results.NotFound();
var result = await authz.AuthorizeAsync(user, doc, Operations.Update);
if (!result.Succeeded)
return Results.NotFound(); // don't confirm another team's document exists
doc.Title = body.Title;
await db.SaveChangesAsync(ct);
return Results.NoContent();
});
// Lists: filter in SQL, never authorise item by item after loading.
docs.MapGet("/", (ClaimsPrincipal user, DocsDb db, CancellationToken ct) =>
{
var userId = user.FindFirstValue("sub")!;
var teamIds = user.FindAll("team_id").Select(c => c.Value).ToArray();
return db.Documents
.Where(d => d.OwnerId == userId || teamIds.Contains(d.TeamId))
.OrderBy(d => d.Id)
.Select(d => new { d.Id, d.Title })
.Take(50)
.ToListAsync(ct);
});
public sealed record UpdateDocument(string Title);
// DocumentAuthorizationHandlerTests.cs (xUnit)
[Theory]
[InlineData("owner", "Delete", true)]
[InlineData("teammate-editor", "Update", true)]
[InlineData("teammate-viewer", "Update", false)]
[InlineData("stranger", "Read", false)]
public async Task Applies_document_rules(string who, string op, bool expected)
{
var doc = new Document { Id = 1, OwnerId = "u1", TeamId = "t1", Title = "Plan" };
var user = Users.Build(who); // test helper building ClaimsPrincipals
var req = new OperationAuthorizationRequirement { Name = op };
var ctx = new AuthorizationHandlerContext([req], user, doc);
await new DocumentAuthorizationHandler().HandleAsync(ctx);
Assert.Equal(expected, ctx.HasSucceeded);
}
RequireAuthorization("documents.write")). Why it is wrong: any user with the scope can edit any document by changing the id. Instead: load the document and call AuthorizeAsync with it.AuthorizeAsync per item. Why it is wrong: slow, breaks paging and leaks counts. Instead: filter in the query or with a global query filter.if (doc.OwnerId != userId) into every endpoint. Why it is wrong: the rules drift and one copy will be wrong. Instead: one handler per resource type with unit tests.User claims set by authentication.AuthorizeAsync(User, await db.Documents.FindAsync(body.Id)) and then db.Documents.Single(d => d.Slug == route.Slug) for the update. Why it is wrong: the check and the action refer to different records, so an attacker passes the check with their own id and edits someone else's. Instead: load once, authorise that instance, modify that same instance.Resource-based authorisation is where most real access-control bugs live, because it can't be declared on the endpoint. I make the safe path the easy path: a service method that loads and authorises in one call, global query filters for tenancy, and a cross-user test suite that runs on every pull request.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
OperationAuthorizationRequirement handler |
Several operations on one resource type | One class per type | A single yes/no rule |
| Named policy with resource requirement | One distinct rule reused across types | Policy registration | Many operations per type |
Query filter / Where |
Lists, searches, exports | Must be applied consistently | Single-record write decisions alone |
| SQL Server row-level security | Defence in depth, shared databases, reporting access | Session context setup, plan impact | As the only check in app code |
Measure it: log authorisation denials by resource type and operation, and alert on a single user hitting many 404s on sequential ids, which is what enumeration looks like.
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.
The EF filter keeps normal code tenant-scoped automatically, so handlers stay simple and nobody forgets a Where. Row-level security enforces the same rule in the database: create a security policy with an inline predicate function comparing TenantId to SESSION_CONTEXT(N'TenantId') (plus a block predicate to stop cross-tenant writes), and set the session context from a DbConnectionInterceptor when each connection opens, with @read_only = 1. Together they're defence in depth: raw SQL, IgnoreQueryFilters or a bug still can't read another tenant's rows. Costs: the predicate runs on every query, so TenantId must lead the relevant indexes or RLS can turn seeks into scans on large tables; debugging is harder because rows silently disappear; and the session context must be set on every connection open because of pooling.
How to tell it (STAR)
**S:** In our [document management] API, a new Delete endpoint was protected only by a scope, so any editor could delete any document in [their tenant]. **T:** I owned the fix and making sure it couldn't happen again. **A:** I hot-fixed the endpoint, restored the deleted documents, and then consolidated every document rule into one resource-based handler with Read, Update and Delete operations and a service method that loads and authorises together. I added second-user integration tests for every endpoint with an id. **R:** We restored [all] affected documents within [a day], found and fixed [four] similar gaps, and the next pen test reported [no] broken object-level authorisation findings.
Last updated 23 Nov 2026.