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

📚 Interview question

Code review: an ASP.NET Core controller for invoices has authorisation enforced only by hiding buttons in the React UI, role strings like "Admin" and "FinanceManager" repeated in attributes, [AllowAnonymous] on the controller 'for the health check', and an Approve action that takes the approver's user id from the request body. What do you flag, in what order, and what does the fixed version look like?

Code review of authorisation: controller-level AllowAnonymous, UI-only checks, missing resource and tenant checks, user id from the request body, scattered role strings, and the rewrite with policies, resource-based authorisation, claims-derived identity, fallback policy and tests.

Senior CodeReview Advanced aspnet-core authorization code-review idor owasp security

🎯 Key points

  • Controller-level [AllowAnonymous] overrides every [Authorize], including explicit action attributes: the whole controller is public (blocking)
  • UI hiding is not authorisation; the API must enforce every rule (blocking)
  • Approver id from the body lets anyone approve as anyone and breaks segregation of duties; take it from claims (blocking)
  • No resource or tenant check on the invoice: BOLA (blocking); AuthorizeAsync with the loaded invoice checks user and record together
  • Role strings scattered: move to named policies or permissions (suggested)
  • Health check belongs on a separate anonymous endpoint (MapHealthChecks), not a controller exception
  • Add a fallback policy, endpoint-metadata test and cross-user tests; audit approvals
  • Log authorisation failures and anonymous calls, alert on spikes, and check logs for past misuse before closing the review

⏱ 30-second answer

I'd rank by exploitability. Blocking: [AllowAnonymous] on the controller makes every action public, because it overrides every [Authorize]; the UI hiding buttons is not authorisation, since anyone can call the API directly; the approver id from the body lets a user approve as someone else and defeats segregation of duties; and there's no resource or tenant check on the invoice (BOLA). Suggested: replace repeated role strings with named policies or permissions.

The rewrite: remove [AllowAnonymous] and move the health check to MapHealthChecks, add a fallback policy, use [Authorize(Policy = ...)], take the user from claims, load the invoice scoped to the tenant and call IAuthorizationService.AuthorizeAsync, block self-approval, and add cross-user tests.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd go through it in order of what an attacker could do today. The first thing I'd flag, and it's blocking, is the [AllowAnonymous] on the controller. In ASP.NET Core, AllowAnonymous anywhere in an endpoint's metadata wins over every [Authorize], so the action-level role attributes do nothing: the whole invoices API is open to the internet. The health check belongs on MapHealthChecks with its own AllowAnonymous, not as an exception on a business controller.

Second, also blocking: the only thing stopping a clerk from approving is that React hides the button. The API is the security boundary; anyone with a token and curl can call POST /invoices/42/approve. Third, the approver id comes from the request body, so I can approve an invoice as my manager, and the audit trail records the wrong person. That breaks segregation of duties, which auditors and [the finance controls] care about, so the id must come from the authenticated user's claims, and the rule 'you can't approve an invoice you raised' belongs in a handler. Fourth, the action loads the invoice by id with no tenant or ownership check, which is broken object-level authorisation. For example, at [company] I [reviewed a pull request with almost exactly this shape]; the fixes took [about a day], and a cross-user test I added [caught the same body-supplied user id pattern in two other controllers].

Then the suggested items: the role strings repeated across attributes should become named policies or permissions, so changing who can approve is one line. I'd close the review with the blocking items as must-fix, a fallback policy and an endpoint-metadata test so this can't recur, and a checklist item for 'user id never from the request'. The senior line: authorisation lives on the server, derives identity from the token, and is checked against the specific record, every time."


Code under review

[ApiController]
[Route("api/invoices")]
[AllowAnonymous]                                              // 1
public class InvoicesController(FinanceDb db) : ControllerBase
{
    [HttpGet("health")]
    public IActionResult Health() => Ok();

    [HttpGet("{id}")]
    [Authorize(Roles = "Admin,FinanceManager,FinanceClerk")] // 5
    public async Task<Invoice?> Get(int id) =>
        await db.Invoices.FindAsync(id);                      // 4, 6

    [HttpPost("{id}/approve")]
    [Authorize(Roles = "Admin,FinanceManager")]               // 5 (2: UI hides the button for clerks)
    public async Task<IActionResult> Approve(int id, ApproveRequest req)
    {
        var invoice = await db.Invoices.FindAsync(id);        // 4
        invoice!.Status = "Approved";
        invoice.ApprovedBy = req.ApproverUserId;              // 3
        await db.SaveChangesAsync();
        return Ok(invoice);                                   // 6
    }
}
public record ApproveRequest(string ApproverUserId);

Findings, ranked by severity

# Severity Finding Fix
1 Security hole Controller [AllowAnonymous] overrides every [Authorize]: all actions public Remove; MapHealthChecks("/healthz").AllowAnonymous()
2 Security hole Approval enforced only by hiding the button in React Policy on the action; the UI mirrors it, never replaces it
3 Security hole Approver id from the body: impersonation, segregation of duties broken, audit falsified Read sub from claims; block self-approval in a handler
4 Security hole FindAsync(id) with no tenant or ownership check (BOLA); null dereference on missing id Tenant-scoped query, resource-based authorisation, 404
5 Design Role strings repeated; easy to typo, hard to audit Named policies or permissions
6 Data exposure / design Returns the entity: internal fields, possible over-posting patterns elsewhere Return a DTO

The rewrite

See the code example: policies registered once, a fallback policy, an InvoiceAuthorizationHandler for tenant and segregation-of-duties rules, identity from claims, a DTO response, and the health check moved out.

How I'd close the review

  • Blocking: 1-4. I'd ask for the fix in this PR and for a quick check of logs for anonymous calls to /api/invoices since the controller shipped.
  • Suggested: 5-6, can be a follow-up PR the same sprint.
  • Guard rails: fallback policy requiring an authenticated user, an endpoint-metadata test that fails on unexpected anonymous endpoints, cross-user and self-approval tests, and a PR checklist line: "user identity never comes from the request".

Production example

After similar fixes on a [finance approvals] service, the endpoint-metadata test flagged [3] more anonymous controllers across the solution, cross-user tests grew to [~60], and the following audit found [no] segregation-of-duties exceptions in the approvals log.

🔍 What the interviewer is checking

Checks whether the candidate can find and rank authorisation flaws in real code, knows ASP.NET Core's metadata precedence, and turns the review into lasting guard rails.

Green flags

  • Spots that controller-level AllowAnonymous disables all [Authorize]
  • States plainly that UI hiding isn't security
  • Flags the body-supplied user id as impersonation and a segregation-of-duties break
  • Finds the missing tenant/resource check
  • Ranks by severity and proposes tests and a fallback policy

Red flags

  • Leads with role-string style issues
  • Accepts UI checks as sufficient
  • Misses the AllowAnonymous precedence

📚 Learn in depth

1. Why AllowAnonymous wins

The authorisation middleware collects the endpoint's metadata. If any item implements IAllowAnonymous, it skips policy evaluation entirely:

metadata: [ApiControllerAttribute, AllowAnonymousAttribute (controller), AuthorizeAttribute(Roles=...) (action)]
  -> IAllowAnonymous present -> authorisation skipped -> anonymous request reaches Approve()

This is by design (it lets a single action opt out of controller-level [Authorize]), which is why AllowAnonymous on a controller or base class is so dangerous.

2. Trust boundaries

Browser (React)          untrusted: hides buttons for UX only
   │  HTTPS + bearer token
API (ASP.NET Core)       trust boundary: every rule enforced here
   │
Database                 last line: tenant filters, RLS

Anything the client sends, including ids in the body, hidden fields, role flags and prices, is attacker-controlled. Identity comes from the validated token only.

3. Segregation of duties

Finance controls often require that the person who raises or modifies an invoice can't approve it, and that approvals over a limit need a second approver. These are authorisation rules about the resource and the user together, so they belong in a resource-based handler (or a domain rule) and must be tested. Writing ApprovedBy from the token makes the audit trail trustworthy.

4. Error and response hygiene

Returning the entity can expose internal columns (CreatedByUserId, TenantId, notes). Null dereference on a missing id produces a 500 and, in misconfigured environments, a stack trace. Use DTOs, return 404, and use ProblemDetails with the developer exception page only in Development.

5. Making it stick

  1. Fallback policy: endpoints without metadata require an authenticated user.
  2. Endpoint-metadata test: unexpected AllowAnonymous fails the build.
  3. Cross-user, cross-tenant and self-approval tests.
  4. Roslyn analyser or architecture test that flags request DTO properties named *UserId on mutating endpoints.

Try it yourself

  1. Reproduce the original controller and call Approve anonymously with curl.
  2. Add the endpoint-metadata test and watch it fail on the controller.
  3. Implement the handler and write tests for: same tenant approver, other tenant (404), self-approval (403).
  4. Write an architecture test (NetArchTest or reflection) that flags request records with a UserId property.

💻 Code

The rewrite: policies in one place, identity from claims, tenant-scoped loading, a resource handler for segregation of duties, and the health check moved out.

// Program.cs (.NET 10)
using Microsoft.AspNetCore.Authorization;
using Finance.Api.Invoices;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddHealthChecks();
builder.Services.AddSingleton<IAuthorizationHandler, InvoiceAuthorizationHandler>();
builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())
    .AddPolicy(InvoicePolicies.Read, p => p.RequireRole("Admin", "FinanceManager", "FinanceClerk"))
    .AddPolicy(InvoicePolicies.Approve, p => p.RequireRole("Admin", "FinanceManager"));
builder.Services.AddControllers();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapHealthChecks("/healthz").AllowAnonymous();   // the only anonymous endpoint, explicitly
app.MapControllers();
app.Run();
// Invoices/InvoicesController.cs
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Finance.Api.Invoices;

public static class InvoicePolicies
{
    public const string Read = "invoices.read";
    public const string Approve = "invoices.approve";
}

public sealed record InvoiceDto(int Id, string Number, decimal Amount, string Status, string? ApprovedBy);

[ApiController]
[Route("api/invoices")]
[Authorize(Policy = InvoicePolicies.Read)]
public sealed class InvoicesController(FinanceDb db, IAuthorizationService authz) : ControllerBase
{
    private string TenantId => User.FindFirstValue("tenant_id")!;
    private string UserId => User.FindFirstValue("sub")!;           // identity from the token only

    [HttpGet("{id:int}")]
    public async Task<ActionResult<InvoiceDto>> Get(int id, CancellationToken ct)
    {
        var dto = await db.Invoices
            .Where(i => i.Id == id && i.TenantId == TenantId)
            .Select(i => new InvoiceDto(i.Id, i.Number, i.Amount, i.Status, i.ApprovedBy))
            .SingleOrDefaultAsync(ct);
        return dto is null ? NotFound() : dto;
    }

    [HttpPost("{id:int}/approve")]
    [Authorize(Policy = InvoicePolicies.Approve)]                    // role gate (AND with Read)
    public async Task<IActionResult> Approve(int id, CancellationToken ct)  // no user id in the request
    {
        var invoice = await db.Invoices.SingleOrDefaultAsync(i => i.Id == id && i.TenantId == TenantId, ct);
        if (invoice is null) return NotFound();

        var check = await authz.AuthorizeAsync(User, invoice, InvoiceOperations.Approve);
        if (!check.Succeeded) return Forbid();

        invoice.Approve(UserId);                                     // domain method enforces status rules
        await db.SaveChangesAsync(ct);
        return NoContent();
    }
}

public static class InvoiceOperations
{
    public static readonly OperationAuthorizationRequirement Approve = new() { Name = nameof(Approve) };
}

public sealed class InvoiceAuthorizationHandler
    : AuthorizationHandler<OperationAuthorizationRequirement, Invoice>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
        OperationAuthorizationRequirement requirement, Invoice invoice)
    {
        var userId = context.User.FindFirstValue("sub");
        var sameTenant = context.User.HasClaim("tenant_id", invoice.TenantId);

        if (requirement.Name == nameof(InvoiceOperations.Approve)
            && sameTenant
            && userId is not null
            && invoice.CreatedBy != userId)                          // segregation of duties
        {
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }
}

⚠ Common mistakes

  • Mistake: Putting [AllowAnonymous] on a controller to expose one action. Why it is wrong: it overrides every [Authorize] on every action. Instead: put it on the single action, or better, move public endpoints out (MapHealthChecks).
  • Mistake: Treating hidden buttons as access control. Why it is wrong: the API is reachable directly with any HTTP client. Instead: enforce every rule in the API; the UI only reflects it.
  • Mistake: Accepting the acting user's id from the body or query. Why it is wrong: the caller can impersonate anyone, and audit records become untrustworthy. Instead: User.FindFirstValue("sub") from the validated token.
  • Mistake: Reviewing role attributes but not record access. Why it is wrong: a FinanceManager in tenant A can still approve tenant B's invoice. Instead: tenant-scoped queries and resource-based checks.
  • Mistake: Flagging style issues (role strings) at the same level as open endpoints. Why it is wrong: the author fixes the easy items and the critical ones get lost. Instead: rank by severity and mark blocking items explicitly.
  • Mistake: Approving the PR once the code is fixed without checking exposure. Why it is wrong: the controller may already have been exploited in production. Instead: check logs for anonymous or cross-tenant calls since it shipped.
  • Mistake: Returning entities from actions. Why it is wrong: internal fields leak, and the same types often get bound on input (over-posting). Instead: DTOs in and out.

🏛 Senior insight: trade-offs

Authorisation review is mostly about trust boundaries: what the server believes and why. I look for three smells first: anything that turns authorisation off (AllowAnonymous, missing policies), anything that takes identity or privileges from the request, and any load by id without a scope. Style issues come after, and I keep them out of the blocking list so the critical fixes don't get diluted.

Review lever Catches Cost Limitation
Severity-ranked review comments This PR's issues Reviewer time Depends on the reviewer
Fallback policy + metadata test Anonymous endpoints, forever One test Doesn't check policy logic
Cross-user / self-approval tests BOLA, segregation of duties Test data Must be written per endpoint
Architecture test for *UserId in request DTOs Identity from the request One test Heuristic, some false positives
Security checklist in the PR template Recurring classes of bugs Discipline Ignored if too long

Measure it: count anonymous endpoints (should be a short, known list), cross-user test coverage of id-taking endpoints, and authorisation findings per pen test over time.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate flags the missing tenant or ownership check Why: Checks they can remediate BOLA across a codebase, not just this controller
    How to answer

    Broken object-level authorisation (BOLA, also called IDOR) is API1:2023 in the OWASP API Security Top 10: the API checks who you are but not whether this object is yours.

    • Fix the endpoint: scope the query by the caller, with callerId read from the token's claims, never from the request (Where(o => o.Id == id && o.CustomerId == callerId)), or load and call IAuthorizationService.AuthorizeAsync when roles or teams are involved; return 404, not 403.
    • Fix the codebase: enumerate every endpoint that takes an id, including child resources and exports; add tenant query filters and optionally row-level security as a safety net.
    • Prevent: cross-user integration tests in CI, a load-and-authorise helper, scheduled access-control reviews and logging that detects enumeration.

    The trade-off: random ids slow attackers down, but they are not authorisation; only a server-side ownership check is.

  2. When: Candidate mentions AllowAnonymous overriding Authorize Why: Checks they understand metadata precedence and how to detect it with tests
    How to answer

    Start with the pipeline and the endpoint metadata, then the logs.

    • Order: UseAuthentication then UseAuthorization, after routing and before endpoints. Middleware that writes a response earlier (custom handlers, UseStaticFiles for a path, a terminal Map) bypasses authorisation.
    • Metadata: does the endpoint actually carry IAuthorizeData, or is there an AllowAnonymous that wins? Endpoints mapped on app instead of the group variable get none of the group's policies.
    • 401 vs 403: 401 means authentication failed or never ran (no default scheme, wrong scheme, issuer or audience mismatch); 403 means a policy denied an authenticated user.

    Enable Microsoft.AspNetCore.Authentication and .Authorization debug logging: it tells you which scheme ran and which requirement failed.

  3. When: Candidate proposes blocking self-approval Why: Checks they can implement the resource-based segregation-of-duties rule
    How to 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.

🛠 Real-world problems: how you handle them

Invoice approvals made anonymously and as other users after a controller shipped with AllowAnonymous
Situation
A [finance approvals] API for [~150] business customers shipped an invoices controller with controller-level `[AllowAnonymous]` (added for a health check) and an Approve action taking the approver id from the body. It was live for [three weeks] before review of a follow-up PR.
Signals
Reviewer spotted the attribute in the follow-up PR; Application Insights showed [a small number of] calls to `/api/invoices/*` with no authenticated user; the audit log had [two] approvals where the recorded approver was [on leave] that day.
Investigation
Dumped endpoint metadata and confirmed every invoices action was anonymous; queried request logs (KQL) for anonymous and cross-tenant calls since release; matched approvals' recorded approver against sign-in logs in Entra ID; with [the finance controller] reviewed the two suspicious approvals.
Resolution
Same day: removed the attribute, moved the health check to `MapHealthChecks`, took the approver from claims, and added tenant-scoped loading with a self-approval rule. The two approvals were reversed and re-approved properly; the incident was reviewed with [the privacy officer and the customer's finance team].
Prevention
Fallback policy in the service template; endpoint-metadata test; architecture test for `UserId` on request DTOs; cross-tenant and self-approval tests; PR checklist item on identity from the token.

How to tell it (STAR)

**S:** Reviewing a follow-up PR on our [finance approvals] API, I noticed the invoices controller had shipped [three weeks] earlier with controller-level `[AllowAnonymous]` and an approve action that trusted an approver id from the body. **T:** I needed to close the hole, find out whether it had been misused and stop it recurring. **A:** I confirmed with endpoint metadata that every action was public, shipped a fix the same day that moved the health check out, derived the approver from the token and added tenant scoping and a segregation-of-duties rule. I queried the logs and matched approvals against Entra sign-ins, which surfaced [two] approvals recorded under the wrong person, and we reversed them with the customer. Then I added a fallback policy, an endpoint-metadata test and an architecture test for user ids in request DTOs. **R:** The fix was live within [four hours], [no] further misuse was found, and the tests have since blocked [three] PRs with the same patterns.

More in Authorization

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me