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.
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.
"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,AllowAnonymousanywhere 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 onMapHealthCheckswith its ownAllowAnonymous, 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."
[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);
| # | 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 |
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.
/api/invoices since the controller shipped.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.
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
AllowAnonymous disables all [Authorize]Red flags
AllowAnonymous precedenceThe 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.
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.
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.
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.
AllowAnonymous fails the build.*UserId on mutating endpoints.UserId property.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;
}
}
[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).User.FindFirstValue("sub") from the validated token.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.
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.
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.The trade-off: random ids slow attackers down, but they are not authorisation; only a server-side ownership check is.
Start with the pipeline and the endpoint metadata, then the logs.
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.IAuthorizeData, or is there an AllowAnonymous that wins? Endpoints mapped on app instead of the group variable get none of the group's policies.Enable Microsoft.AspNetCore.Authentication and .Authorization debug logging: it tells you which scheme ran and which requirement failed.
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.
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.
Last updated 23 Nov 2026.