Risk Assessment & Management

Preventing BOLA in Your API: How to Enforce Object-Level Authorization in Every Endpoint

Stop broken object level authorization (BOLA) with deny-by-default policy, owner-scoped queries and two-user regression tests. Why UUIDs alone fail.

Written by
Engr Mejba Ahmed
Published
Reading time
11 min
Preventing BOLA in Your API: How to Enforce Object-Level Authorization in Every Endpoint

If your API returns or changes a record because the request names its ID, any authenticated user who edits that ID may be able to read or modify someone else's data. This guide shows how to enforce object-level authorization in one central place, why random identifiers do not replace it, and how to prove the fix with two-user regression tests that run on every build.

What Broken Object Level Authorization Actually Is

Broken object level authorization (BOLA) is closely tied to CWE-639: Authorization Bypass Through User-Controlled Key. MITRE describes the weakness as a system whose "authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data." The attacker is usually an authenticated user. Login works, session handling works, and the endpoint still hands over any record whose key the caller supplies.

The key can sit almost anywhere the client controls. CWE lists a hidden HTML form field, a URL parameter and an unencrypted cookie as examples, and notes that in each case the value can be tampered with. In an API, the same applies to path segments, query strings, JSON bodies and custom headers. Any value that reaches a database lookup without an entitlement check is a candidate.

The impact depends on what the key unlocks. CWE describes horizontal escalation, where one user can view or modify another user's information, as the main consequence. It also notes that vertical escalation is possible "if the user-controlled key is actually a flag that indicates administrator status." A field such as role or is_admin accepted from the request body is a key in this sense.

Two points of precision matter. First, CWE lists BOLA as an alternate term that "appears to have some overlap" with CWE-639, while noting that BOLA "may be applicable to other weaknesses in addition to this one." Treat CWE-639 as the core root cause, not the full definition. Second, CWE-639 is listed as a member of the 2025 CWE Top 25 Most Dangerous Software Weaknesses view, which is a reasonable signal for prioritising it in design reviews.

Enforce Ownership Centrally with Deny-by-Default and Scoped Lookups

The CWE entry's primary mitigation is blunt: "For each and every data access, ensure that the user has sufficient privilege to access the record that is being requested." The difficulty is doing that consistently across dozens or hundreds of handlers. An if statement copied into each endpoint will eventually be forgotten in one of them.

The OWASP Authorization Cheat Sheet addresses this directly. It recommends that permission be validated on every request, and that the technology performing those checks "should allow for global, application-wide configuration rather than needing to be applied individually to every method or class." It also recommends deny-by-default and warns that explicit configuration should be preferred over framework or library defaults, because third-party defaults can change without the developer noticing. As the cheat sheet puts it, an attacker only needs to find one way in.

The OWASP IDOR Prevention Cheat Sheet adds the data-layer half: "When looking up objects based on primary keys, use datasets that users have access to." In practice, that means the query itself includes the owner, so a record belonging to someone else is never loaded.

The following is an xCyberSecurity design recommendation, written as framework-agnostic pseudocode. It combines three parts: identity resolved only from server-side state, a repository method scoped to the owner, and a policy function that denies anything not explicitly granted.

# Design recommendation (pseudocode): central object-level authorization

middleware authenticate(request):
    session = verify_session_or_token(request)
    if session is invalid: return 401
    request.user = session.user        # identity from server state only
    # never take user or owner IDs from path, query, body or cookies

function policy(user, action, document):
    if action == "read"   and document.owner_id == user.id: return ALLOW
    if action == "update" and document.owner_id == user.id: return ALLOW
    if action == "delete" and document.owner_id == user.id: return ALLOW
    return DENY                        # anything not granted is denied

function get_document(id, user):
    doc = db.query("SELECT * FROM documents WHERE id = ? AND owner_id = ?",
                   id, user.id)
    if doc is None: raise NotFound     # missing and not-owned look identical
    return doc

handler update_document(request, id):
    doc = get_document(id, request.user)
    if policy(request.user, "update", doc) == DENY: raise NotFound
    apply_changes(doc, request.body)

The middleware runs once for every route, so no handler can skip authentication. The repository never loads another user's document. The policy function looks redundant for plain ownership, but it is where rules go when the model grows, for example shared documents or a separate export permission. Because its last line returns DENY, a new action such as "export" is refused until someone writes a rule that grants it.

There is a tradeoff between scoped lookups and post-fetch checks. The IDOR cheat sheet shows both patterns: querying by ID and owner together, or fetching by ID and then comparing the owner. It notes that the post-fetch check "can distinguish a missing object from one the caller cannot access." That is useful for internal diagnostics but can leak whether a record exists. Scoped lookups avoid the leak by design. Post-fetch checks are sometimes unavoidable when ownership is computed from several tables, and in that case map the denial to the same response as a missing record.

One failure case to watch: the scoped repository method exists, but a developer adds a reporting endpoint that calls the raw find_by_id instead. Restrict direct, unscoped lookups to a small, reviewed module so that the safe path is also the easy one. For broader identity design, see Identity & Access Security.

A single funnel filters a stream of requests so only records matching the caller's owner mark pass, showing central deny-by-default policy and owner-scoped queries.

Why Random or Encrypted IDs Do Not Fix BOLA

Sequential integer IDs make tampering trivial, so teams often respond by switching to UUIDs or encrypting identifiers. Both change how hard a valid ID is to guess. Neither checks whether the caller is entitled to the record.

The OWASP Authorization Cheat Sheet says that while IDs can be masked or randomized to make them hard to guess, "such an approach is generally not sufficient by itself." It adds that a user should not be able to access a resource simply because they can guess and manipulate its identifier, and that the focus should be on controlling access to the underlying objects. Identifiers leak through shared links, logs, browser history, email notifications and other API responses. Once an attacker holds a valid ID, randomness offers no protection.

The IDOR Prevention Cheat Sheet treats complex random identifiers as defense in depth only, suggesting a random-string column or UUIDs in place of enumerable numeric keys. It also says: "Avoid encrypting identifiers as it can be challenging to do so securely."

The two sources differ on this point. CWE-639 lists "Use encryption in order to make it more difficult to guess other legitimate values of the key or associate a digital signature with the key so that the server can verify that there has been no tampering" as an architectural mitigation. OWASP advises against encryption specifically. A practical reading is that both treat the key as a secondary control: CWE's first-listed mitigation is still a privilege check on every access. If you sign or encrypt keys, keep the ownership check anyway.

Two patterns remove the problem rather than obscure it:

  • Server-derived references. The Authorization Cheat Sheet recommends avoiding exposed identifiers where possible and retrieving objects such as account details based solely on the authenticated user's identity, for example from a server-side session. An endpoint like /me/account has no client-supplied key to tamper with.
  • Uniform responses. The IDOR cheat sheet recommends that when a resource's existence is sensitive, you "use the scoped lookup and map both cases to the same public response, such as a 404 (Not Found) response."

Prove It with Two-User Regression Tests and Access Logging

Central enforcement only helps if you can show it covers every route. The IDOR Prevention Cheat Sheet describes a simple method: create User A and User B, create objects owned by each, authenticate as User A and attempt to access User B's objects by modifying references. It states this verification "should be performed for all operations involving object references, including read, create, update, delete, export, and administrative actions," and that access should be denied whether the identifier is predictable or unguessable.

The following is a proposed test scenario in pseudocode. It checks that cross-user requests are refused without changing data, and that the owner's own requests still succeed.

# Proposed test scenario (pseudocode): two-user BOLA regression matrix

setup:
    userA = create_user(); userB = create_user()
    docA  = create_document(owner=userA)
    docB  = create_document(owner=userB)

endpoints = [
    ("GET",    "/documents/{id}"),
    ("GET",    "/documents/{id}/export"),
    ("PUT",    "/documents/{id}"),
    ("DELETE", "/documents/{id}"),      # last: removes docA
]

for (method, path) in endpoints:
    before = snapshot(docB)
    resp = request_as(userA, method, path.format(id=docB.id))
    assert resp.status in (403, 404)
    assert snapshot(docB) == before     # no state change
    assert docB.content not in resp.body

    resp = request_as(userA, method, path.format(id=docA.id))
    assert resp.status in (200, 204)    # owner access still works

The positive assertion matters as much as the negative one. A test that only checks for refusals will pass on an endpoint that refuses everyone. If your policy is to return the same 404 for missing and unauthorized objects, tighten the assertion to 404 only, so a stray 403 that confirms existence fails the build.

Extend the matrix to the operations the loop does not cover. For create, have User A submit a new document with owner_id set to User B and assert the stored owner is User A or the request is rejected. For administrative routes, add a non-admin user and include any request field that could act as a role flag, reflecting CWE's vertical-escalation case. Generate the endpoint list from your route table where possible, so a new route without a test entry is flagged rather than silently skipped.

Tests show what you thought to check. Logging shows what happens in production. The Authorization Cheat Sheet warns that "if logging related to access control is not properly set-up, such authorization violations may go undetected or at least remain unattributable to a particular individual or group." Log every denial from the policy function and the scoped repository with the user ID, object type, route and timestamp. Leave request bodies and record contents out of the log. A single user generating a run of not-found or denied responses across different object IDs is a pattern worth alerting on.

Perimeter controls cannot do this work for you, because they do not know who owns a given record. For related perimeter context, see Stop Mirai Botnets: AWS WAF + API Gateway Security Playbook.

Two color-coded data cards and a test beam show User A being blocked from User B's record while still reaching its own, with denials written to a log.

FAQ

Is BOLA the same as IDOR? Not exactly. CWE-639 lists both Insecure Direct Object Reference and BOLA as alternate terms, but says the OWASP IDOR term is broader because it also covers path traversal, and that BOLA may apply to other weaknesses too. CWE also notes that, as of CWE 4.20, the relationship between IDOR and BOLA needs to be investigated more closely.

Do UUIDs prevent BOLA? No. OWASP treats complex random identifiers as defense in depth and says randomizing IDs is generally not sufficient by itself. The server must still check access on every request.

Should we encrypt object IDs? OWASP's IDOR Prevention Cheat Sheet advises avoiding it because it is hard to do securely. CWE-639 lists encryption or signing as a mitigation. Whichever you choose, keep the ownership check.

Can a WAF or API gateway stop BOLA? As a design matter, no. A gateway sees a valid token and a well-formed ID; it has no knowledge of which user owns which record. Object-level checks belong in the application and data layer.

Where should the check live in a framework? The Authorization Cheat Sheet points to globally configurable mechanisms, such as Java/Jakarta EE filters including Spring Security, Django middleware, .NET Core filters and Laravel middleware. Configure them explicitly rather than relying on defaults.

Rolling Out Object-Level Authorization Across Your Endpoints

Start with an inventory: list every route that accepts an object identifier in the path, query, body, header or cookie, and mark which ones use an owner-scoped lookup today. Move authentication into middleware so identity always comes from server-side state, and route all data access for user-owned records through scoped repository methods. Put a deny-by-default policy function in front of every action, including export and administrative operations.

Next, add the two-user regression matrix to CI with both negative and positive assertions, and decide on one public response for missing and unauthorized objects. Keep UUIDs as a speed bump against enumeration, not as the control. Finally, log every authorization denial without sensitive payloads and alert on repeated cross-object failures from one account, so a missed check is noticed before it becomes a data exposure.

Want an independent check of your own setup? See Penetration Testing by xCyberSecurity.

Engr Mejba Ahmed
Written by

Engr Mejba Ahmed

I'm Engr. Mejba Ahmed, a Software Engineer, Cybersecurity Engineer, and Cloud DevOps Engineer specializing in Laravel, Python, WordPress, cybersecurity, and cloud infrastructure. Passionate about innovation, AI, and automation.