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

📚 Interview question

A penetration test finds broken object-level authorisation (IDOR) in your API: changing the order id in GET /api/orders/{id} returns another customer's order. How do you fix this one endpoint, and how do you make sure the same flaw doesn't exist anywhere else in the codebase?

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.

Senior Security Advanced authorization ef-core idor owasp-api-security penetration-testing security

🎯 Key points

  • BOLA is API1:2023 in the OWASP API Security Top 10; Broken Access Control leads the OWASP Top 10
  • Root cause: the endpoint trusts the id and checks only authentication or a scope
  • Fix: scope the query by the caller (Where CustomerId == callerId) or resource-based AuthorizeAsync; return 404
  • Defence in depth: EF Core global query filters for tenant, SQL Server row-level security underneath
  • Opaque or random ids reduce enumeration but are not authorisation
  • Find every instance: list endpoints with id parameters, grep for FindAsync/Find by id, review service methods, check exports and child resources
  • Prevent: cross-user integration tests in CI, load-and-authorise helpers, architecture tests, review checklist
  • Assess impact from logs (sequential-id access by one user) and against the NDB scheme

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

🗣 Full answer (senior)

How I would answer this in an interview

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

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


The vulnerability

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

Layers of the fix

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

Production example

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.

🔍 What the interviewer is checking

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

  • Names BOLA / API1:2023 and explains the root cause precisely
  • Scopes the query by the caller from the token and returns 404
  • Hunts for other instances, including exports, child resources and writes
  • Adds cross-user tests and tenant filters or RLS as layers
  • Checks logs for exploitation and mentions the NDB scheme

Red flags

  • Thinks GUIDs fix it
  • Fixes only the one endpoint
  • Takes the user id from the request

📚 Learn in depth

1. Why BOLA is so common

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 }

2. Fix patterns

  1. Scope the query. Where(o => o.Id == id && o.CustomerId == callerId). Cheapest and naturally returns 404.
  2. Resource-based authorisation. Load, then AuthorizeAsync(User, order, Operations.Read). Use when rules involve roles, teams or state.
  3. Route through the caller. /api/me/orders/{id} makes the scope explicit in the design, though the server still has to enforce it.

3. Defence in depth

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.

4. Finding every instance

  • Enumerate endpoints from EndpointDataSource and list those with route parameters named id or ending in Id.
  • Grep for FindAsync(, .Find(, FirstOrDefaultAsync(x => x.Id == in handlers and services.
  • Don't forget non-JSON responses: file downloads, CSV exports, signed URLs to Blob Storage (a SAS for another customer's file is the same bug), webhook replay endpoints and job-status endpoints.
  • Check write paths too: PUT and DELETE are often less tested than GET.
  • Check object property level issues (API3:2023): the caller may own the object but shouldn't change Status or CreditLimit (over-posting).

5. Ids

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.

6. Detecting exploitation

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

Try it yourself

  1. Build the vulnerable endpoint below and exploit it with two test users in an integration test.
  2. Fix it by scoping the query; confirm the test now gets 404.
  3. Write a test that enumerates endpoints with id route parameters and fails when one has no matching cross-user test.
  4. Add an EF Core global query filter for TenantId and try to bypass it with FromSql; then add an RLS policy and try again.
  5. Write the KQL query that would detect one user requesting more than 50 distinct order ids in 10 minutes.

💻 Code

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

⚠ Common mistakes

  • Mistake: Switching ids to GUIDs and closing the finding. Why it is wrong: ids leak through URLs, emails and logs; the endpoint still returns any object. Instead: a server-side ownership check, with opaque ids as an extra.
  • Mistake: Fixing only the reported endpoint. Why it is wrong: the same pattern is almost always in sibling endpoints, exports and child resources. Instead: enumerate every endpoint that takes an id and test each one cross-user.
  • Mistake: Taking customerId from the query string or body. Why it is wrong: the attacker sets it. Instead: read it from the authenticated user's claims.
  • Mistake: Returning 403 for other customers' objects. Why it is wrong: it confirms existence and helps enumeration. Instead: 404 for both missing and not yours.
  • Mistake: Using simple ownership checks where roles also matter (support staff, account managers, delegated access). Why it is wrong: teams then add ad-hoc 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.
  • Mistake: Relying on a tenant query filter as the whole fix. Why it is wrong: it doesn't stop customer B reading customer A's order in the same tenant, and IgnoreQueryFilters or raw SQL bypass it. Instead: ownership in the query or a resource handler, with filters as a safety net.
  • Mistake: Securing GET but not PUT, DELETE or file downloads. Why it is wrong: writes and exports are equally exploitable and often worse. Instead: cover every verb and every response type, including SAS URLs.
  • Mistake: Treating the annual pen test as the only check. Why it is wrong: new endpoints ship every sprint and BOLA reappears between tests. Instead: CI cross-user tests, a quarterly access-control review of new endpoints, and periodic review of enumeration alerts and denial logs.
  • Mistake: Not checking logs for exploitation. Why it is wrong: the organisation may have a notifiable breach. Instead: look for enumeration patterns and involve the privacy officer for an NDB assessment.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions defence in depth or tenant filters Why: Checks they know how to combine EF Core tenant filters with SQL Server row-level security
    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.

  2. When: Candidate mentions PUT endpoints or API3:2023 Why: Checks they also recognise object property level authorisation (over-posting)
    How to answer

    I'd rank the findings by impact:

    1. Security: it loads by id with no ownership check (an IDOR), and mapping the whole DTO allows over-posting of fields like Status or OwnerId.
    2. Wrong data: no concurrency token, so concurrent edits are silently lost; and the mapper may replace child collections, orphaning or deleting lines.
    3. Waste: Update() on an already-tracked entity is redundant and marks every column modified.
    4. Robustness and design: a missing record throws a 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.

🛠 Real-world problems: how you handle them

Pen test finds customers can read each other's orders by changing the id
Situation
A [retail] e-commerce API on Azure (Australia East) with [~400k] customer accounts had sequential integer order ids. The annual pen test by [an external firm] reported that `GET /api/orders/{id}` returned any order to any signed-in customer, including name, delivery address and items.
Signals
Pen-test report rated it Critical; Application Insights showed [two] non-tester accounts in the past [90] days requesting more than [200] distinct order ids each; customer support had [one] earlier complaint about 'seeing someone else's order' that had been closed as a caching issue.
Investigation
Reproduced with Burp Suite using two test accounts; enumerated every endpoint with an id parameter from `EndpointDataSource` and wrote cross-user tests, finding [nine] more vulnerable endpoints including an invoice PDF export; queried request logs with KQL for enumeration patterns; worked with [the privacy officer] to assess the [two] suspicious accounts' access against the NDB scheme.
Resolution
Within [24 hours]: hot-fixed the orders and invoice endpoints with caller-scoped queries returning 404, and blocked the suspicious accounts. Over [two sprints]: fixed the remaining endpoints, introduced service methods that require the caller, added a tenant query filter for the B2B side, and moved public order references to opaque ids.
Prevention
Cross-user integration tests mandatory for every id-taking endpoint (enforced by a CI test that lists endpoints); enumeration alert in Azure Monitor; definition of done updated; pen-test retest confirming closure.

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.

↩ Usually asked after

More in Authorization

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me