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

📚 Interview question

Write a custom authorisation handler in ASP.NET Core. Show a requirement and an AuthorizationHandler that uses a DI service, explain how multiple handlers for the same requirement combine, when to call Succeed versus Fail, and how you register and test the handler.

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.

Mid-Level Coding Intermediate aspnet-core authorization authorization-handler dependency-injection security testing

🎯 Key points

  • Requirement = immutable data (record) implementing IAuthorizationRequirement
  • AuthorizationHandler<TRequirement>.HandleRequirementAsync calls context.Succeed(requirement) as soon as the rule holds
  • Any handler succeeding satisfies the requirement; context.Fail() vetoes it regardless
  • Register as IAuthorizationHandler; scoped if it needs DbContext; handlers are resolved from the request scope
  • Returning without Succeed means 'this handler doesn't grant it', not a failure; Fail() only for definite denial, with an AuthorizationFailureReason
  • Since .NET 8, IAuthorizationRequirementData lets an attribute like [RequiresFeature("payslips")] carry requirements
  • Keep handlers fast: cache lookups with a short TTL and invalidate on change; no outbound calls without a timeout
  • Unit test with AuthorizationHandlerContext directly; integration test with WebApplicationFactory

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 interface IAuthorizationRequirement, and I make it a record so it's immutable. The handler derives from AuthorizationHandler<ActiveSubscriptionRequirement>, takes its dependencies through the constructor, say an ISubscriptionReader and TimeProvider, and in HandleRequirementAsync it reads the tenant id from the user's claims, checks the subscription and calls context.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 an AuthorizationFailureReason so 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 a DbContext. 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 an AuthorizationHandlerContext directly, and integration test the endpoint with WebApplicationFactory. The senior line: a handler answers one question and returns quickly; anything slower belongs in a cache or in the token."


Succeed, do nothing or Fail

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

Lifetimes

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

Where handlers fit

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can implement a real authorisation handler, understands the evaluation semantics, and handles DI lifetimes, performance and testing.

Green flags

  • Separates requirement (data) from handler (logic)
  • Knows multiple handlers mean OR and Fail means veto
  • Registers scoped handlers when they need scoped services
  • Caches lookups and unit tests the handler directly
  • Mentions IAuthorizationRequirementData or failure reasons

Red flags

  • Calls Fail for every negative case
  • Puts business data lookups in the handler with no thought for cost
  • Can't explain how to test it

📚 Learn in depth

1. What happens when a policy is evaluated

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

2. Why OR across handlers, AND across requirements

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

3. Handler resolution and lifetimes

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

4. Requirement data on attributes (.NET 8+)

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

5. Failure reasons and the response

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

6. Cost

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

Try it yourself

  1. Implement the subscription handler below and unit test the three outcomes: succeed, no decision, fail.
  2. Add InternalStaffHandler and prove OR semantics with a test.
  3. Register the handler as a singleton that depends on DbContext and watch ValidateScopes throw in Development.
  4. Benchmark the handler with and without HybridCache using BenchmarkDotNet.
  5. Write an IAuthorizationMiddlewareResultHandler that returns ProblemDetails with a safe failure code.

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

⚠ Common mistakes

  • Mistake: Calling 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.
  • Mistake: Registering a handler that uses 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.
  • Mistake: A database or HTTP call on every request with no cache or timeout. Why it is wrong: it adds hidden latency to every protected endpoint and can hang the request. Instead: cache per user or tenant with a short TTL, and fail closed on timeout.
  • Mistake: Caching authorisation facts with only a TTL. Why it is wrong: a suspension or plan downgrade keeps working until the entry expires. Instead: remove the entry (or its tag with HybridCache.RemoveByTagAsync) when the underlying data changes, and keep the TTL short as a backstop.
  • Mistake: Several handlers each doing the same expensive lookup. Why it is wrong: every registered handler runs for every evaluation, so the cost multiplies. Instead: share one cached reader, or load the data once in claims transformation.
  • Mistake: Putting several unrelated checks in one handler. Why it is wrong: you lose the OR/AND composition and the failure reason is vague. Instead: one requirement per rule, composed in policies.
  • Mistake: Making requirements mutable or storing per-request state in them. Why it is wrong: requirements live in cached policies shared across requests. Instead: immutable records; per-request data comes from context.User or context.Resource.
  • Mistake: Only testing with an always-authorised test user. Why it is wrong: the deny paths are never exercised. Instead: unit test the handler with AuthorizationHandlerContext and integration test 401/403 paths.
  • Mistake: Returning detailed failure reasons to the caller. Why it is wrong: it tells an attacker what to change. Instead: log the reason, return a generic 403 or a coarse problem type.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate reads claims such as tenant_id in the handler Why: Checks they understand how authentication produces the ClaimsPrincipal the handler reads
    How to answer

    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.

  2. When: Candidate mentions AuthorizationFailureReason or support tickets about 403s Why: Checks they know IAuthorizationMiddlewareResultHandler and avoid leaking internal detail
    How to answer

    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.

🛠 Real-world problems: how you handle them

Suspended tenants still reached payroll endpoints because a staff handler overrode the check
Situation
A multi-tenant [payroll SaaS] with [~600] tenants used a policy where `ActiveSubscriptionHandler` and `InternalStaffHandler` both handled one requirement. Finance suspended [a tenant for non-payment], but [the tenant's staff accounts that also had a support flag] could still run pay runs.
Signals
Finance reported pay runs created by a suspended tenant; Application Insights showed 200 responses on `/payruns` for that tenant after the suspension time; no authorisation failures logged.
Investigation
Turned on `Microsoft.AspNetCore.Authorization` debug logs in a staging copy and replayed the requests; confirmed that the staff handler called `Succeed` on the same requirement, so OR semantics allowed access regardless of suspension; reviewed all handlers for where suspension was enforced and found it was only checked in the UI.
Resolution
Immediate: disabled the support flag on the tenant's accounts. Fix: added a `SuspendedTenantHandler` that calls `Fail` with a failure reason (a veto), mapped that reason to a `tenant-suspended` problem type, and invalidated the cached plan on suspension.
Prevention
Unit tests for every handler combination (staff + suspended must deny); an ADR documenting when to use `Fail`; a metric on authorisation failures by reason with an alert when suspended-tenant denials stop appearing after a suspension event.

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

↩ Usually asked after

More in Authorization

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me