BOLA testing in ASP.NET Core: catch broken object level authorization before an AI agent does
Your API checks the token, the token is valid, and the request returns 200 OK. The data belongs to someone else.
That is Broken Object Level Authorization (BOLA), number one on the OWASP API Security Top 10. Authentication passes and authorization never runs. Nothing crashes and nothing is logged as an error. One customer simply reads another customer's invoice.
The risk is growing because API callers are changing. Scripts, integrations and AI agents hold long-lived tokens and work through IDs systematically. A person who sees /invoices/1041 might try 1042out of curiosity. An agent asked to "summarise all invoices" will try every ID it can find. This post shows how BOLA appears in ASP.NET Core, how to fix it, and how to write an integration test that fails the build when it comes back.
What BOLA looks like in ASP.NET Core
app.MapGet("/invoices/{id:guid}", async (Guid id, AppDb db) =>
{
var invoice = await db.Invoices.FindAsync(id);
return invoice is null ? Results.NotFound() : Results.Ok(invoice);
})
.RequireAuthorization();RequireAuthorization()only checks that someone is signed in. It doesn't check whether this invoice is theirs. Any authenticated user who has or guesses an ID gets the record.
Why "we use GUIDs" is not a fix
Random IDs make guessing harder, but IDs leak all the time: in URLs pasted into support tickets, webhook payloads, browser history, logs, and list responses from other endpoints. An agent that has read one response may already hold IDs it should never use. Unguessable IDs are defence in depth, never the control.
Fixing it: three patterns
1. Filter by owner in the query
app.MapGet("/invoices/{id:guid}", async (Guid id, ClaimsPrincipal user, AppDb db) =>
{
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
var invoice = await db.Invoices
.Where(i => i.Id == id && i.OwnerId == userId)
.SingleOrDefaultAsync();
return invoice is null ? Results.NotFound() : Results.Ok(invoice);
})
.RequireAuthorization();Records you don't own come back as not found, so the endpoint never confirms that someone else's ID exists.
2. Resource-based authorization
When access depends on roles, sharing or state, use ASP.NET Core's resource-based authorization:
public sealed class InvoiceOwnerHandler
: AuthorizationHandler<OperationAuthorizationRequirement, Invoice>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
OperationAuthorizationRequirement requirement,
Invoice invoice)
{
var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
if (invoice.OwnerId == userId)
context.Succeed(requirement);
return Task.CompletedTask;
}
}
// Program.cs
builder.Services.AddSingleton<IAuthorizationHandler, InvoiceOwnerHandler>();
app.MapDelete("/invoices/{id:guid}", async (
Guid id, ClaimsPrincipal user, AppDb db, IAuthorizationService auth) =>
{
var invoice = await db.Invoices.FindAsync(id);
if (invoice is null) return Results.NotFound();
var result = await auth.AuthorizeAsync(
user, invoice, new OperationAuthorizationRequirement { Name = "Delete" });
if (!result.Succeeded) return Results.NotFound(); // don't confirm it exists
db.Invoices.Remove(invoice);
await db.SaveChangesAsync();
return Results.NoContent();
})
.RequireAuthorization();3. EF Core global query filters
For tenant isolation, a global query filter adds the tenant condition to every query on the entity:
public class AppDb(DbContextOptions<AppDb> options, ITenantContext tenant)
: DbContext(options)
{
public DbSet<Invoice> Invoices => Set<Invoice>();
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<Invoice>().HasQueryFilter(i => i.TenantId == tenant.TenantId);
}| Pattern | Best for | Weak spot |
|---|---|---|
| Owner filter in the query | Simple "my records" APIs | Has to be repeated on every query |
| Resource-based authorization | Sharing, roles, state-dependent rules | Easy to forget the AuthorizeAsync call |
| Global query filter | Tenant isolation | Bypassed by IgnoreQueryFilters() or raw SQL |
In practice: a global filter for the tenant boundary, plus an owner filter or a resource-based check for user-level rules.
Writing a BOLA regression test
One account can't prove BOLA is absent. You need two users and one object, and the test has to show the second user can't touch it. ASP.NET Core's integration testing support makes this cheap. Start with an authentication handler that signs in whoever the test names in a header:
public sealed class TestAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string Scheme = "Test";
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.TryGetValue("X-Test-User", out var user))
return Task.FromResult(AuthenticateResult.NoResult());
var identity = new ClaimsIdentity(
[new Claim(ClaimTypes.NameIdentifier, user.ToString())], Scheme);
return Task.FromResult(AuthenticateResult.Success(
new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme)));
}
}Add public partial class Program { } at the end of Program.cs so the test project can reference it. Then the cross-user tests:
public class InvoiceBolaTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
private HttpClient ClientFor(string userId)
{
var client = factory.WithWebHostBuilder(b => b.ConfigureTestServices(s =>
s.AddAuthentication(TestAuthHandler.Scheme)
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
TestAuthHandler.Scheme, _ => { })))
.CreateClient();
client.DefaultRequestHeaders.Add("X-Test-User", userId);
return client;
}
[Theory]
[InlineData("GET")]
[InlineData("PUT")]
[InlineData("DELETE")]
public async Task Other_user_cannot_reach_invoice(string method)
{
var alice = ClientFor("alice");
var bob = ClientFor("bob");
var created = await alice.PostAsJsonAsync("/invoices", new { amount = 120 });
created.EnsureSuccessStatusCode();
var invoice = await created.Content.ReadFromJsonAsync<InvoiceDto>();
var request = new HttpRequestMessage(new HttpMethod(method), $"/invoices/{invoice!.Id}");
if (method == "PUT")
request.Content = JsonContent.Create(new { amount = 1 });
var response = await bob.SendAsync(request);
Assert.True(
response.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.Forbidden,
$"{method} returned {(int)response.StatusCode} for another user's invoice");
// The owner's data must be unchanged
var check = await alice.GetFromJsonAsync<InvoiceDto>($"/invoices/{invoice.Id}");
Assert.Equal(120, check!.Amount);
}
[Fact]
public async Task List_only_returns_own_invoices()
{
var alice = ClientFor("alice");
var bob = ClientFor("bob");
await alice.PostAsJsonAsync("/invoices", new { amount = 50 });
var bobsList = await bob.GetFromJsonAsync<List<InvoiceDto>>("/invoices");
Assert.All(bobsList!, i => Assert.Equal("bob", i.OwnerId));
}
private sealed record InvoiceDto(Guid Id, string OwnerId, decimal Amount);
}Two details matter:
- The ownership check at the end. A
PUTthat returns404after it has already written the change is still a BOLA. Read the record back as the owner. - The list test checks the body. List and search endpoints rarely return
403. They leak by including rows that shouldn't be there, so the status code can't catch it.
BOLA test checklist
- Two users with different ownership, and two tenants if you're multi-tenant
- Every verb on every
{id}route: GET, PUT, PATCH, DELETE - Nested routes such as
/users/{userId}/orders/{orderId}: test both IDs - List, search, export and download endpoints, checking the body
- IDs in request bodies and query strings, not only in the path
- Archived, soft-deleted and draft objects
- A lower-privilege user against admin-owned objects
- After a denied write, confirm the record didn't change
Common mistakes
- Only checking the status code. A
200with someone else's data passes a naive test. - Fixing the controller but not the background job or GraphQL resolver that reads the same table.
- Trusting a user ID from the route or body instead of the authenticated principal.
- Returning
403for other people's records. It confirms the ID exists. Prefer404unless your contract says otherwise. - Testing with seeded admin accounts. Admins can see everything, so the test passes for the wrong reason.
Why AI agents raise the stakes
Agents don't create a new vulnerability. They make an existing one easier to hit. An agent with a broadly scoped token follows every ID it sees in responses, retries with variations, and reports what it found to a user who may not own it. Two practical steps:
- Give agent integrations narrowly scoped tokens tied to one user or tenant, never a shared service account that can read everything.
- Run your BOLA tests against the endpoints you expose to agents or through MCP tools. A tool that wraps
GET /invoices/{id}inherits that endpoint's authorization exactly.
FAQ
Is BOLA the same as IDOR?
Practically, yes. IDOR (Insecure Direct Object Reference) is the older name. OWASP uses BOLA for APIs.
Should a BOLA failure return 403 or 404?
404 avoids confirming the object exists. 403 is fine when the caller is already allowed to know it exists, for example inside their own organisation. Pick one and test for it consistently.
Does [Authorize] prevent BOLA?
No. [Authorize] and RequireAuthorization() check who the caller is, not whether they own the record.
Can a scanner find BOLA for me?
Scanners help, but they don't know your ownership rules. Integration tests written by people who know the data model are the most reliable regression guard.
Do GraphQL APIs have BOLA?
Yes. Every resolver that takes an ID needs the same check, including nested resolvers.
Conclusion
BOLA persists because it looks like success: a valid token, 200 OK, well-formed JSON. The fix is usually one Whereclause. The hard part is noticing it's missing. Put the ownership check where the data is read, write a two-user test for every route that takes an ID, and check the response body as well as the status. The OWASP Authorization Cheat Sheet covers the wider design rules, and our authentication track covers the token side.