← Back to FastAPI, page 5

fastapi-0100 · Hard senior

How do you prevent broken object level authorization (BOLA, also called IDOR) in FastAPI endpoints?

BOLA happens when an authenticated user can read or change another user's object by changing an ID in the URL, because the code checks who the caller is but not whether the object belongs to them. Prevent it by centralising ownership checks in a dependency that loads the object scoped to the current user (or tenant) and returns 404 otherwise, filtering list queries the same way, using policy functions for roles, and testing cross-user access for every route.

Full answer

BOLA is first in the OWASP API Security Top 10. Authentication ("who are you?") does not imply authorization ("may you touch this record?"). Hard-to-guess IDs (UUIDs) reduce guessing but are not a control: IDs leak through logs, links and other endpoints.

Defences:

  1. Scope queries by owner at the data access layer: select(Note).where(Note.id == note_id, Note.owner_id == user.id). If no row is returned, respond 404 (not 403) so you do not reveal that the object exists. Return 403 only when the existence is public and the action is forbidden.
  2. Put the pattern in a reusable dependency:
python
def owned_note(note_id: int, user: CurrentUser, db: DB) -> Note:
    note = db.scalar(select(Note).where(Note.id == note_id, Note.owner_id == user.id))
    if note is None:
        raise HTTPException(404, "Note not found")
    return note

Every route that takes note_id declares note: Annotated[Note, Depends(owned_note)], so developers cannot forget the check and the code stays DRY. For shared resources, a policy function decides: can(user, "edit", note) based on ownership, team membership or role. 3. Apply the same scope to list, search, export and aggregate endpoints, and to nested resources (/classes/{id}/students/{sid} must verify both). 4. Never accept the owner or tenant from the request body (owner_id in JSON): derive it from the token. Use separate input and output models (mass assignment protection). 5. Admin access: explicit role checks with audit logging. 6. Background jobs and webhooks need the same checks, since they act on behalf of users. 7. In multi-tenant systems add database-level protection, such as PostgreSQL Row-Level Security. 8. Test: for each endpoint create objects as user A and assert user B receives 404 for read, update and delete, and list never includes A's data. Automate with parametrised tests over the OpenAPI routes, and add authorization tests to code review checklists.

Related: BFLA (broken function level authorization, such as normal users calling admin endpoints) needs role or scope checks per route.

python
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel

NOTES = {1: {"id": 1, "owner": "asha", "text": "asha private"}, 2: {"id": 2, "owner": "ravi", "text": "ravi private"}}
TOKENS = {"token-asha": "asha", "token-ravi": "ravi"}                       # stand-in for real JWT validation
app = FastAPI()


def current_user(authorization: Annotated[str, Header()] = "") -> str:
    user = TOKENS.get(authorization.removeprefix("Bearer "))
    if user is None:
        raise HTTPException(401, "Invalid credentials", headers={"WWW-Authenticate": "Bearer"})
    return user


User = Annotated[str, Depends(current_user)]


def owned_note(note_id: int, user: User) -> dict:
    note = NOTES.get(note_id)
    if note is None or note["owner"] != user:                              # same answer for "missing" and "not yours"
        raise HTTPException(404, "Note not found")
    return note


class NoteUpdate(BaseModel):
    text: str                                                              # no owner field: it cannot be set by clients


@app.get("/notes")
def list_notes(user: User):
    return [n["text"] for n in NOTES.values() if n["owner"] == user]


@app.get("/notes/{note_id}")
def read(note: Annotated[dict, Depends(owned_note)]):
    return note


@app.put("/notes/{note_id}")
def update(body: NoteUpdate, note: Annotated[dict, Depends(owned_note)]):
    note["text"] = body.text
    return note


# Vulnerable version for comparison: authenticates but never checks ownership
@app.get("/unsafe/notes/{note_id}")
def unsafe_read(note_id: int, user: User):
    return NOTES[note_id]


c = TestClient(app)
asha, ravi = {"Authorization": "Bearer token-asha"}, {"Authorization": "Bearer token-ravi"}
print("own note:", c.get("/notes/1", headers=asha).status_code)
print("someone else's note:", c.get("/notes/2", headers=asha).status_code, "| missing note:", c.get("/notes/99", headers=asha).status_code)
print("update other's note:", c.put("/notes/2", json={"text": "hacked"}, headers=asha).status_code, "| text now:", NOTES[2]["text"])
print("list is scoped:", c.get("/notes", headers=ravi).json())
print("owner field ignored on update:", c.put("/notes/1", json={"text": "edited", "owner": "ravi"}, headers=asha).json())
print("unsafe route leaks:", c.get("/unsafe/notes/2", headers=asha).json()["text"])
print("no token:", c.get("/notes/1").status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): own note: 200 someone else's note: 404 | missing note: 404 update other's note: 404 | text now: ravi private list is scoped: ['ravi private'] owner field ignored on update: {'id': 1, 'owner': 'asha', 'text': 'edited'} unsafe route leaks: ravi private no token: 401

Key points

  • Authentication does not imply authorization for a specific object
  • Load objects scoped to the current user in a shared dependency
  • Return 404 for objects the caller may not know exist
  • Filter lists and nested resources the same way
  • Derive owner or tenant from the token and test cross-user access

Common mistakes

  • Checking authentication but not ownership
  • Relying on unguessable UUIDs as the only protection
  • Returning 403 and revealing which IDs exist
  • Accepting owner_id or tenant_id from the request body
  • Scoping single-object routes but forgetting list, export and nested routes

Follow-ups

  • How does PostgreSQL row-level security complement this?
  • How would you model team-shared objects?
  • What is BFLA and how does it differ?

Tips

  • Show the ownership dependency
  • Say 404 over 403
  • Mention cross-user tests