Broken object-level authorisation (OWASP API1:2023, IDOR): vulnerable code and exploit, ownership in the query, resource-based authorisation, tenant query filters and RLS, opaque ids, finding every affected endpoint, cross-user tests, logging enumeration, and NDB assessment.
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.
"BOLA, or IDOR, is the most common serious API finding, which is why OWASP lists it first in the API Security Top 10. The endpoint is authenticated, maybe it even checks a scope, but it loads
Orders.Find(id)and returns it, so any signed-in customer can walk the ids. The one-line fix is to make the query itself answer the authorisation question:Where(o => o.Id == id && o.CustomerId == callerId), with the caller id coming from the token, never from the request. If nothing comes back, I return 404, so the attacker can't even tell which ids exist. Where the rule is richer than ownership, I use a resource-based handler withIAuthorizationService.The real work is the rest of the codebase, because a pen tester finding one IDOR usually means the pattern is everywhere. For example, at [company] after a pen test found [one] IDOR on orders, I [listed every endpoint with an id parameter from the endpoint data source, about 140], triaged them by data sensitivity, and wrote a cross-user test for each: customer B requests customer A's resource and must get 404. That suite found [nine] more, including [an invoice PDF export and a nested /orders/{id}/notes endpoint] that the pen testers hadn't reached. We added an EF Core global query filter on
TenantIdas a safety net, and moved loading into service methods that always take the caller.I'd also check the logs to see whether it was exploited: one account requesting many sequential ids is the signature. If personal information was accessed, that goes to [the privacy officer] for assessment under the Notifiable Data Breaches scheme. The mistake I see is switching to GUIDs and calling it fixed. The senior line: unguessable ids are a speed bump; authorisation is a server-side check on every object, enforced by tests."
| Element | Detail |
|---|---|
| OWASP | API1:2023 Broken Object Level Authorization; A01 Broken Access Control in the OWASP Top 10 |
| Root cause | Object loaded by a client-supplied id with no ownership or tenant check |
| Where it hides | Child resources, file downloads, exports, GraphQL resolvers, bulk endpoints, background-job status endpoints |
| Exploit | Signed in as customer B, request /api/orders/1001, 1002, ... |
| Layer | Mechanism | Catches |
|---|---|---|
| Endpoint | Query scoped by caller or AuthorizeAsync |
The reported bug |
| Data access | Global query filter on TenantId; service methods take the caller |
Forgotten checks within a tenant boundary |
| Database | SQL Server row-level security with SESSION_CONTEXT |
Bugs that bypass EF Core (raw SQL, reporting) |
| Tests | Cross-user and cross-tenant integration tests | Regressions in CI |
| Monitoring | Alert on one user hitting many distinct ids with 404s | Active enumeration |
For a [retail] API with [~400k] customer accounts, the remediation found [10] BOLA endpoints in total. All were fixed within [two sprints]; the cross-user suite of [~140] tests runs in [about 90 seconds] in CI, and the enumeration alert fired [once] in the following six months, on a [misbehaving partner integration] rather than an attacker.
Checks whether the candidate treats IDOR as a systemic access-control problem: an exact fix, defence in depth, finding every instance, prevention and incident handling.
Green flags
Red flags
Frameworks make authentication declarative and make loading by id trivial. Nothing in [Authorize] or RequireAuthorization knows about ownership, so unless the team deliberately puts the caller into every query, the default code is vulnerable:
GET /api/orders/1002 Authorization: Bearer <customer B token>
-> [Authorize] passes (B is authenticated)
-> db.Orders.FindAsync(1002) (belongs to A)
-> 200 OK { customer A's name, address, items }
Where(o => o.Id == id && o.CustomerId == callerId). Cheapest and naturally returns 404.AuthorizeAsync(User, order, Operations.Read). Use when rules involve roles, teams or state./api/me/orders/{id} makes the scope explicit in the design, though the server still has to enforce it.Controller / endpoint ownership check (primary control)
↓
Service layer GetOrderForCustomer(id, caller) (single path to data)
↓
EF Core HasQueryFilter(o => o.TenantId == _tenant.Id)
↓
SQL Server RLS: security policy using SESSION_CONTEXT('TenantId')
Query filters protect tenant boundaries but not ownership within a tenant, and they can be bypassed with IgnoreQueryFilters or raw SQL. RLS covers raw SQL and reporting connections but needs the session context set reliably (for example in a connection interceptor) and has plan-cache and performance considerations.
EndpointDataSource and list those with route parameters named id or ending in Id.FindAsync(, .Find(, FirstOrDefaultAsync(x => x.Id == in handlers and services.Status or CreditLimit (over-posting).Sequential integers make enumeration trivial; random GUIDs or opaque ids make it impractical. That reduces exploitability and is worth doing for public identifiers, but ids leak through URLs, logs, emails and referrers, so they must never be the control.
KQL in Application Insights: requests by user id where distinct resource ids > N in 10 minutes and 404 rate is high. Correlate with the pen-test window to separate testers from real attackers. If personal information of other customers was returned, the organisation must assess the incident under the NDB scheme (30 days to assess a suspected eligible data breach).
TenantId and try to bypass it with FromSql; then add an RLS policy and try again.Vulnerable: authenticated, but any customer can read any order.
// Exploit in one line: signed in as customer B, request GET /api/orders/1002 (customer A's order).
app.MapGet("/api/orders/{id:int}", async (int id, ShopDb db, CancellationToken ct) =>
await db.Orders.FindAsync([id], ct) is { } order ? Results.Ok(order) : Results.NotFound())
.RequireAuthorization();
Fixed: the query is scoped by the caller from the token, returns a DTO, and a miss is a 404.
// Orders/OrderEndpoints.cs (.NET 10)
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
namespace Shop.Api.Orders;
public sealed record OrderDto(int Id, DateTimeOffset PlacedAt, decimal Total, string Status);
public static class OrderEndpoints
{
public static RouteGroupBuilder MapOrders(this RouteGroupBuilder group)
{
group.MapGet("/{id:int}", async (int id, ClaimsPrincipal user, ShopDb db, CancellationToken ct) =>
{
var customerId = user.FindFirstValue("customer_id"); // from the token, never the request
if (customerId is null) return Results.Forbid();
var order = await db.Orders
.Where(o => o.Id == id && o.CustomerId == customerId)
.Select(o => new OrderDto(o.Id, o.PlacedAt, o.Total, o.Status))
.SingleOrDefaultAsync(ct);
return order is null ? Results.NotFound() : Results.Ok(order); // same answer for 'not yours' and 'missing'
});
return group;
}
}
// ShopDb.cs: tenant safety net (protects tenant boundaries, not ownership within a tenant)
public sealed class ShopDb(DbContextOptions<ShopDb> options, ITenantContext tenant) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<Order>().HasQueryFilter(o => o.TenantId == tenant.TenantId);
}
// CrossUserTests.cs: one per endpoint that takes an id
[Fact]
public async Task Customer_cannot_read_another_customers_order()
{
var orderOfA = await _seed.CreateOrderAsync(customerId: "A");
var clientB = _factory.CreateClientFor(customerId: "B"); // test auth handler issues B's claims
var response = await clientB.GetAsync($"/api/orders/{orderOfA.Id}");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
// Application Insights: possible enumeration (one user, many distinct ids, mostly 404s)
requests
| where timestamp > ago(1h) and name startswith "GET /api/orders/"
| summarize ids = dcount(url), notFound = countif(resultCode == "404") by user_AuthenticatedId, bin(timestamp, 10m)
| where ids > 50 and notFound > ids * 0.5
customerId from the query string or body. Why it is wrong: the attacker sets it. Instead: read it from the authenticated user's claims.if (IsInRole("Support")) bypasses that become new holes. Instead: a resource-based handler that encodes owner, delegate and staff rules in one tested place, with staff access audited.IgnoreQueryFilters or raw SQL bypass it. Instead: ownership in the query or a resource handler, with filters as a safety net.A BOLA finding is a process finding, not a bug. The fix that matters is making the vulnerable shape hard to write: data access that always takes the caller, cross-user tests that run on every pull request, and a tenant safety net beneath. I also use the finding to change the definition of done for any endpoint with an id.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Caller-scoped query | Ownership rules | Lowest; naturally 404 | Complex role or team rules |
| Resource-based handler | Roles, teams, state rules | A handler per resource type | Simple ownership |
| Global query filter (tenant) | Multi-tenant apps | Must set tenant reliably | As the only control |
| SQL Server RLS | Shared databases, reporting, raw SQL | Session context, performance testing | Single-tenant, simple apps |
| Opaque ids | Public-facing identifiers | Migration of existing ids | As a substitute for checks |
Measure it: the number of id-taking endpoints without a cross-user test (target zero), denial rates per endpoint, and enumeration alerts. Report the trend to the security lead, not only the fixed count.
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.
I'd rank the findings by impact:
Status or OwnerId.Update() on an already-tracked entity is redundant and marks every column modified.NullReferenceException (500, not 404), and it returns the entity instead of a DTO.The rewrite: a use-case DTO with only editable fields plus RowVersion, load filtered by owner, set the RowVersion original value, assign fields explicitly, SaveChangesAsync, and map DbUpdateConcurrencyException to 409. The trade-off is a few lines of explicit mapping in exchange for correct, minimal, secure updates.
How to tell it (STAR)
**S:** Our annual pen test on a [retail] API with [~400k] customers found that any signed-in customer could read any order by changing the id, and logs showed [two] accounts had already enumerated hundreds of orders. **T:** I led the technical response and the remediation. **A:** I hot-fixed the endpoint within [a day] with a query scoped by the customer id from the token, returning 404 for anything not theirs. Then I enumerated all [~140] endpoints that take an id and wrote a cross-user test for each, which found [nine] more, including an invoice PDF export. I worked with [the privacy officer] on the NDB assessment, added a tenant query filter, opaque public ids and an enumeration alert. **R:** All [ten] endpoints were fixed within [two sprints], the retest came back clean, and the CI check has blocked [two] new endpoints that lacked a cross-user test.
Last updated 23 Nov 2026.