📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show how you implement resource-based authorisation in ASP.NET Core, for example 'only the document's owner or an editor in the same team may edit it'. Why can't a policy on the endpoint do this alone, and how do you use IAuthorizationService.AuthorizeAsync with the loaded resource?

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.

Mid-Level Coding Intermediate aspnet-core authorization ef-core idor resource-based-authorization security

🎯 Key points

  • Endpoint policies run before the handler, so they can't see the record being accessed
  • AuthorizationHandler<TRequirement, TResource> receives the loaded resource as context.Resource
  • OperationAuthorizationRequirement (Read/Update/Delete) gives one handler per resource type covering owner, team, viewer and admin rules
  • Load, then IAuthorizationService.AuthorizeAsync(User, doc, Operations.Update), then act on that same object
  • Return 404 instead of 403 when existence is sensitive: a 403 confirms the id is real and enables enumeration
  • Include resource state (Paid, Archived, Locked) and least privilege: grant each role only the operations it needs
  • Lists: filter in the query (Where OwnerId == userId or tenant filter), not item-by-item after loading
  • Test as two different users: the second must get 403/404

⏱ 30-second answer

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.

  • Write an AuthorizationHandler<TRequirement, TResource>, usually with OperationAuthorizationRequirement (Read, Update, Delete) so one handler holds every rule for a resource type: owner, team editor, viewer, admin.
  • In the endpoint, load the record, call IAuthorizationService.AuthorizeAsync(User, document, Operations.Update), and return Forbid(), or NotFound() when even confirming the record exists would disclose information.
  • For lists, filter in the database query; never load everything and check one by one.

The trade-off: it's imperative, so a developer can forget the call. Back it with tests and query filters.

🗣 Full answer (senior)

How I would answer this in an interview

"Policies on the endpoint answer questions about the user: are they signed in, do they have the editor role or the documents.write scope. '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 from AuthorizationHandler<OperationAuthorizationRequirement, Document>, and in the endpoint I load the document, then call IAuthorizationService.AuthorizeAsync(User, document, Operations.Update). If it fails I return Forbid(), or NotFound() if even knowing the document exists would leak something, which is usually the case for customer data.

I like OperationAuthorizationRequirement because 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 of if statements 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 a DocumentAuthorizationHandler with 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 explicit Where for ownership. The senior line: the endpoint policy is the front door, resource-based authorisation is the lock on each room, and you need both."


Where each check belongs

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

403 or 404?

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows why endpoint policies can't protect individual records and can implement resource-based authorisation correctly, including lists.

Green flags

  • Explains that middleware runs before the resource is loaded
  • Uses AuthorizationHandler<TRequirement, TResource> and IAuthorizationService
  • Chooses 404 over 403 when existence is sensitive
  • Filters lists in the query and mentions query filters
  • Tests with a second user

Red flags

  • Thinks a role or scope check is enough
  • Takes the user id from the request
  • Authorises lists after loading them

📚 Learn in depth

1. Why the middleware can't do it

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.

2. The handler signature

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.

3. Lists and query filters

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.

4. Avoiding the forgotten call

The weakness of imperative checks is that someone forgets them. Mitigations:

  1. Load-and-authorise helpers in a service layer (GetForUpdateAsync(id, user)), so endpoints never load an entity without a check.
  2. A cross-user integration test per endpoint: user B tries user A's id.
  3. Code review checklist and an analyser or architecture test for endpoints that take an {id} route value.

5. Field-level and state rules

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.

Try it yourself

  1. Implement the handler below and write a table-driven xUnit test for every role/operation combination.
  2. Write a WebApplicationFactory test where user B requests user A's document and asserts 404.
  3. Compare the SQL for filtering a list in the query versus authorising each item after ToListAsync, with 10,000 rows.
  4. Add a global query filter for TenantId and confirm it applies to Included navigations.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Relying on the endpoint policy alone (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.
  • Mistake: Loading a list and filtering with AuthorizeAsync per item. Why it is wrong: slow, breaks paging and leaks counts. Instead: filter in the query or with a global query filter.
  • Mistake: Returning 403 for other customers' records. Why it is wrong: it confirms the id exists, so an attacker can map which ids are real and target them. Instead: return 404 when existence is sensitive.
  • Mistake: Copying 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.
  • Mistake: Taking the user id from the request body or query. Why it is wrong: the caller controls it. Instead: read it from User claims set by authentication.
  • Mistake: Authorising one object and changing another, for example 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.
  • Mistake: Ignoring resource state. Why it is wrong: an owner editing a submitted or paid record can bypass a business process. Instead: include state in the handler for access rules, and keep invariants in the domain entity.
  • Mistake: Giving every role every operation "for now". Why it is wrong: it breaks least privilege, so a viewer account compromise becomes a delete. Instead: map each role to the minimum set of operations in the handler and test the denials.
  • Mistake: Only testing as the owner. Why it is wrong: the deny path is never exercised. Instead: a second-user test for every endpoint with an id.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate writes the document handler Why: Checks they can write and test the handler itself, including Succeed vs Fail
    How to answer

    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).

    • Several handlers for one requirement combine as OR: any Succeed is enough.
    • Fail() is a veto that denies even if another handler succeeded, so use it only for a definite no (suspended account).
    • Since .NET 8, 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.

  2. When: Candidate mentions global query filters or multi-tenant data Why: Checks defence in depth for tenant data below the application layer
    How to answer

    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.

🛠 Real-world problems: how you handle them

Team members could delete each other's documents after a role change
Situation
A [document management] API for [~200] business customers let editors update documents in their team. A change added a Delete endpoint protected only by the `documents.write` scope policy.
Signals
A customer reported documents disappearing; audit logs showed deletes by users who weren't the owner; Application Insights showed 204s on `DELETE /documents/{id}` from [a single editor account].
Investigation
Reviewed the endpoint and found no resource check; searched the codebase for endpoints with an `{id}` route value and no `AuthorizeAsync` call, finding [four]; replayed the delete as a non-owner in a test environment to confirm.
Resolution
Same day: hot-fixed the Delete endpoint with an ownership check and restored the documents from soft-delete. Then moved all document rules into a `DocumentAuthorizationHandler` with operations and a `GetForUpdateAsync` helper that loads and authorises in one call.
Prevention
Cross-user integration tests for every endpoint with an id; an architecture test that fails when a document endpoint injects `DocsDb` directly instead of the authorising service; pull request checklist item for new operations.

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.

↩ Usually asked after

More in Authorization

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me