How-To Guide

How to Prevent Broken Access Control

Enforce authorization on every request at the object level, deny by default, and test it adversarially so a missing check cannot leak data.

On this page

  1. Introduction
  2. What Broken Access Control Is
  3. Deny by Default
  4. Object-Level Checks on Every Request
  5. Enforcement at Every Entry Point
  6. Testing Authorization Adversarially
  7. Common Failures
  8. Conclusion

Introduction

Broken access control is consistently the most common serious web vulnerability: a user can read or change data that belongs to someone else because a check is missing, applied to the wrong thing, or applied only in the user interface. The classic form is insecure direct object reference, where changing an id in a URL returns another user’s record because the endpoint checked that the user was logged in but not that the record was theirs. This article covers object-level authorization, deny by default, enforcement at every entry point, and adversarial testing that finds the missing check before an attacker does.

What Broken Access Control Is

Access control decides whether a principal may perform an action on a resource. It breaks when a request is not checked at all, when the check is on the wrong resource, when it trusts a client-supplied value such as a role in a request body, or when it is enforced only in the UI so a direct API call bypasses it. The result is a user performing an action they should not.

The most common concrete form is the insecure direct object reference: an endpoint that takes an id and returns the object without confirming the caller owns it. Because ids are often sequential or guessable, an attacker enumerates them and reads other users’ data. The fix is an object-level check, not a hidden id.

Deny by Default

Start from denial and add allowances, rather than starting from allow and adding exceptions. A new endpoint or a new field should be inaccessible until someone explicitly permits it, so forgetting to add a check fails closed. Starting from allow means a forgotten check is a hole, and there will always be forgotten checks.

Deny by default applies at several levels: the route, the resource and the field. An endpoint that returns a resource should return only the fields the caller may see, so a new sensitive field does not leak by being added to the model. A serializer that includes everything by default leaks the day a field is added.

Object-Level Checks on Every Request

The check must confirm that this caller may act on this specific object, and it must run on every request, not only on the list view. A common pattern is to scope the query by the caller’s identity so the database itself filters, returning not-found when the object belongs to someone else, which also avoids leaking existence.

// Scope every query by the authenticated principal so a missing filter
// is impossible: the caller cannot accidentally read another user's row.
async function getInvoice(db, authUser, invoiceId) {
  const { rows } = await db.query(
    `SELECT * FROM invoices
      WHERE id = $1
        AND tenant_id = $2           -- the caller's tenant
        AND (owner_id = $3 OR $4)    -- owner, or an explicit admin override
      LIMIT 1`,
    [invoiceId, authUser.tenantId, authUser.userId, authUser.isAdmin],
  );
  if (rows.length === 0) throw new NotFound();   // do not reveal existence
  return rows[0];
}

// A mutation checks the same scope before writing.
async function updateInvoice(db, authUser, invoiceId, changes) {
  const invoice = await getInvoice(db, authUser, invoiceId); // reuse the check
  if (!invoice) throw new NotFound();
  if (invoice.status === 'paid') throw new Conflict('immutable after payment');
  // ...apply the update within the same scoped transaction...
}

Enforcement at Every Entry Point

A service usually has more entry points than the HTTP route: a background job, a queue consumer, a websocket message, an internal admin API. Each must enforce the same authorization, because the internal channel is reachable by anything that can publish to it. A check only on the HTTP path leaves the other paths open.

Centralise the authorization so it cannot be forgotten per route: a middleware that requires an authenticated principal, plus a per-resource check that the query enforces. The middleware covers the “logged in” question and the scoped query covers the “may access this object” question, and every new endpoint inherits both. This mirrors validating input at the boundary once, rather than per field.

Testing Authorization Adversarially

Test that an authorized user can do the thing, and also that an unauthorized user cannot. Create data for two users, authenticate as one, and attempt to read and write the other’s objects: by direct id, through every endpoint, and by tampering with any client-supplied field such as owner_id or role. These tests must run against the real authorization, because a mock would not exercise it.

Automate the cross-user test so it runs for every endpoint, because the missing check is usually on a new endpoint whose author copied the shape of an old one and forgot the scope. A parametrised test that walks a list of endpoints and asserts a 404 or 403 for another user’s object catches the regression the day it is introduced.

// A parametrised cross-tenant test: user A must never touch user B's rows.
const endpoints = [
  { method: 'GET',  path: (id) => `/api/invoices/${id}` },
  { method: 'PATCH', path: (id) => `/api/invoices/${id}`, body: { total: 0 } },
  { method: 'DELETE', path: (id) => `/api/invoices/${id}` },
];

describe('authorization is enforced per object', () => {
  for (const ep of endpoints) {
    it(`rejects ${ep.method} on another tenant's invoice`, async () => {
      const { invoiceId } = await createInvoiceFor(tenantB);
      const res = await request(app)
        .to(ep.path(invoiceId))
        .method_ // (pseudo) called with tenant A credentials
        .auth(tenantA.token);
      expect([403, 404]).toContain(res.status);   // denied or hidden
    });
  }
});

Common Failures

The frequent failures are: trusting a role or an owner id from the request body; checking authentication but not authorization; enforcing in the UI only; using a sequential id that invites enumeration and relying on that id being hard to guess; and applying the check on read but not on write, so a user can change a record they cannot see. Each is a missing or misplaced check.

A subtler failure is privilege escalation through mass assignment: an endpoint that binds the whole request body to a model lets a user set a field the UI never exposes, such as is_admin. Bind only the fields the caller may change, and treat every field not explicitly allowed as forbidden rather than permitted by default.

Conclusion

Prevent broken access control by denying by default, scoping every query by the authenticated principal so the database enforces object-level authorization, and applying the same check at every entry point rather than only the HTTP route. Return not-found for another user’s object so existence does not leak, bind only permitted fields, and test adversarially with two users attempting to access each other’s data through every endpoint. Then a missing check fails closed and is caught in CI rather than by an attacker.

Sources: OWASP Top 10: Broken Access Control, OWASP: Authorization Cheat Sheet, OWASP: IDOR.

FAQ

What is an insecure direct object reference?
An endpoint that takes an object id and returns the object without confirming the caller owns it. Because ids are often guessable, an attacker enumerates them and reads other users data. The fix is an object-level ownership check, not a hidden id.
Why scope the query by the principal instead of checking after fetching?
Scoping makes the missing check impossible: the database filters to the caller rows, and a request for another user object returns not-found. Checking after fetching is easy to forget on a new code path, and it also reveals existence.

Related Examples