Lab: Roles and Ownership Checks in FastAPI
Implement declarative role-based access control and resource ownership checks using reusable FastAPI dependency injection providers, and verify cross-tenant isolation with pytest.
Contentsand lesson path
On this page
- Lab overview and objectives
- Defence in depth: layered authorization
- Step 1: AuthN and role dependency providers
- Step 2: resource ownership validation and anti-enumeration
- Step 3: verification test suite
- Step 4: swap the mock tokens for signed JWTs
- Check your understanding
- Apply it
- Review prompt
Lessons of Authentication & Authorization
- Identity, Credentials and Permission Models (RBAC, ABAC, ReBAC) Concept · 20 min
- Storing Passwords So a Breach Is Not a Disaster Worked example · 20 min
- Sessions, Tokens or API Keys? Trade-offs and Pitfalls Concept · 30 min
- Delegated Login with OAuth 2.0 and OpenID Connect, and Stopping Token Replay Concept · 30 min
- Lab: Roles and Ownership Checks in FastAPI Lab · 30 min
- Check: Spot the Authorization Bug Knowledge check · 10 questions
What you will learn
- Enforce role-based and object-level authorization in one central place, and prove with tests that one user cannot read or change another user's resources.
- Compare server-side sessions with signed tokens (JWT) and implement one correctly, including cookie flags, expiry, refresh rotation, revocation and signature and claim validation.
Prerequisites: HTTP & APIs
01. Lab overview and objectives
Broken Object Level Authorization (BOLA) is the first risk (API1) in the OWASP API Security Top 10 (2023). When an API verifies that a client is authenticated but neglects to check whether the authenticated user actually owns or has rights to the specific entity identified in the URL (such as /api/v1/invoices/9921), any authenticated user can read or tamper with another customer's sensitive records.
In a multi-tenant SaaS platform, a BOLA bug can expose one customer's records to another, which can also bring fines under laws such as GDPR or HIPAA. An is_admin flag or a valid JWT says who the caller is, not which records they may touch.
In this lab, you will build a small, declarative authorization layer in FastAPI and practise four authorization patterns:
- Declarative authentication dependency: Extracting and validating the authenticated user via FastAPI's
Dependssystem. - Role enforcement factory: Building parameterizable role dependencies (
require_roles("admin", "manager")) to guard sensitive administrative endpoints. - Granular ownership verification: Validating that a requested resource belongs to the current user's tenant or user ID, returning an opaque HTTP 404 to prevent resource existence enumeration attacks.
- Automated security testing: Writing pytest test suites that assert member vs. admin capabilities and confirm cross-user data isolation.
A last step replaces the mock tokens with signed JWTs, to show that the authorization layer does not depend on how callers are authenticated.
02. Defence in depth: layered authorization
A secure backend does not rely on a single gatekeeper. It checks access in three layers, an approach called defence in depth:
- Tier 1, edge gateway (authentication): Verifies credential validity, decodes cryptographically signed tokens, checks token revocation, and attaches the resolved identity to request context. If credentials are missing or expired, the request is rejected immediately with HTTP 401 Unauthorized.
- Tier 2, route and role guard: Evaluates coarse-grained capabilities before executing database queries. For example, ensuring the caller has the role
adminor the OAuth scopebilling:write. If the caller lacks the required role, the request is halted with HTTP 403 Forbidden. - Tier 3, entity ownership and tenant boundary: Evaluates fine-grained ownership after looking up the specific entity in the database. Verifies that
entity.tenant_id == current_user.tenant_idandentity.owner_id == current_user.user_id. If unauthorized, the server responds with HTTP 404, so the answer does not reveal whether the entity exists.
03. Step 1: AuthN and role dependency providers
Rather than copying authorization code into every route handler, put each check in a reusable dependency function. FastAPI resolves a handler's dependencies before the handler runs, sub-dependencies first: require_roles declares user = Depends(get_current_user), so get_current_user runs first, and the role check runs only if it returned a user instead of raising 401. Token parsing stays out of the route handlers.
Set up a project folder auth-lab/ with empty app/__init__.py and tests/__init__.py, and a virtual environment with FastAPI, httpx2 (the HTTP client that current TestClient releases use) and pytest, as below (tested with Python 3.12.13). Then create app/security.py with the user model and role verification factory. The Authorization header is declared optional on purpose: with a required Header(...), FastAPI would answer a request without the header with its own 422 validation error before your code runs, so clients would never see the 401 and the WWW-Authenticate: Bearer challenge that RFC 6750 asks for:
mkdir -p auth-lab/app auth-lab/tests && cd auth-lab
touch app/__init__.py tests/__init__.py
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "fastapi==0.165.0" "httpx2==2.16.2" "pytest==9.2.0"from dataclasses import dataclass
from fastapi import Depends, Header, HTTPException, status
@dataclass
class AuthenticatedUser:
user_id: str
tenant_id: str
role: str
# Mock database of active authenticated sessions
SESSIONS = {
"token_alice": AuthenticatedUser("usr_alice", "tenant_a", "member"),
"token_bob": AuthenticatedUser("usr_bob", "tenant_b", "member"),
"token_charlie": AuthenticatedUser("usr_admin", "tenant_a", "admin"),
}
async def get_current_user(
authorization: str | None = Header(default=None),
) -> AuthenticatedUser:
"""Validate bearer token and resolve authenticated user identity."""
# Optional header: a missing one must give 401, not FastAPI's 422
scheme, _, token = (authorization or "").partition(" ")
user = SESSIONS.get(token) if scheme.lower() == "bearer" else None
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing, malformed or unknown bearer token",
headers={"WWW-Authenticate": "Bearer"}, # RFC 6750 challenge
)
return user
def require_roles(*allowed_roles: str):
"""Factory generating dependency that enforces user roles."""
async def role_checker(
user: AuthenticatedUser = Depends(get_current_user),
) -> AuthenticatedUser:
if user.role not in allowed_roles:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Action requires one of roles: {allowed_roles}",
)
return user
return role_checker04. Step 2: resource ownership validation and anti-enumeration
A crucial security decision is what HTTP status code to return when user A attempts to access user B's resource.
If you return 403 Forbidden, an attacker learns that resource inv_9921 exists, which helps enumeration and targeted attacks. Returning 404 Not Found for both "missing" and "not yours" gives an unauthorized caller no way to tell the two apart.
Every project carries a tenant_id, and the loader checks it first, for everyone. An admin may see any project of their own tenant, but an admin of tenant A must not reach tenant B. Deletion reuses the same loader after the role guard, so the destructive route cannot skip the ownership check. Here is app/main.py:
from fastapi import Depends, FastAPI, HTTPException, status
from app.security import AuthenticatedUser, get_current_user, require_roles
app = FastAPI(title="Project Management API")
# Mock database storing projects keyed by ID
PROJECTS = {
"proj_1": {"id": "proj_1", "name": "Alice Secret",
"tenant_id": "tenant_a", "owner_id": "usr_alice"},
"proj_2": {"id": "proj_2", "name": "Bob Finances",
"tenant_id": "tenant_b", "owner_id": "usr_bob"},
"proj_3": {"id": "proj_3", "name": "Dana Roadmap",
"tenant_id": "tenant_a", "owner_id": "usr_dana"},
}
async def get_project_with_ownership(
project_id: str,
current_user: AuthenticatedUser = Depends(get_current_user),
) -> dict:
"""Load a project the caller may see: own project, or any in the tenant
for a tenant admin. The tenant check applies to everyone, admins too."""
project = PROJECTS.get(project_id)
allowed = (
project is not None
and project["tenant_id"] == current_user.tenant_id
and (project["owner_id"] == current_user.user_id
or current_user.role == "admin")
)
if not allowed:
# 404, not 403: do not reveal that another tenant's record exists
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Project not found",
)
return project
@app.get("/v1/projects/{project_id}")
async def read_project(project: dict = Depends(get_project_with_ownership)):
return project
@app.delete("/v1/projects/{project_id}")
async def delete_project(
# Role first (403 for members), then the same tenant-scoped loader
admin_user: AuthenticatedUser = Depends(require_roles("admin")),
project: dict = Depends(get_project_with_ownership),
):
del PROJECTS[project["id"]]
return {"status": "deleted", "project_id": project["id"]}Before writing tests, try three requests by hand. Save this as check.py in auth-lab/ and run python check.py. TestClient calls the app in the same process, so no server is needed:
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
for token, project in [("token_alice", "proj_1"), ("token_alice", "proj_2"),
(None, "proj_1")]:
headers = {"Authorization": f"Bearer {token}"} if token else {}
r = client.get(f"/v1/projects/{project}", headers=headers)
print(token, project, r.status_code, r.json().get("detail", "ok"))token_alice proj_1 200 ok
token_alice proj_2 404 Project not found
None proj_1 401 Missing, malformed or unknown bearer token05. Step 3: verification test suite
Now write tests/test_authz.py. The fixture restores PROJECTS after each test, because the delete tests change module state. The named tests cover the main rules, and the permission matrix at the end runs one row per (caller, method, project) combination:
import copy
import pytest
from fastapi.testclient import TestClient
from app import main
@pytest.fixture
def client():
saved = copy.deepcopy(main.PROJECTS) # tests delete projects: restore
yield TestClient(main.app)
main.PROJECTS.clear()
main.PROJECTS.update(saved)
def as_user(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
def test_alice_can_read_own_project(client):
r = client.get("/v1/projects/proj_1", headers=as_user("token_alice"))
assert r.status_code == 200 and r.json()["owner_id"] == "usr_alice"
def test_alice_cannot_read_bobs_project(client):
r = client.get("/v1/projects/proj_2", headers=as_user("token_alice"))
assert r.status_code == 404
def test_alice_cannot_delete_as_member(client):
r = client.delete("/v1/projects/proj_1", headers=as_user("token_alice"))
assert r.status_code == 403 and "proj_1" in main.PROJECTS
def test_admin_can_delete_project_in_own_tenant(client):
r = client.delete("/v1/projects/proj_3", headers=as_user("token_charlie"))
assert r.status_code == 200 and "proj_3" not in main.PROJECTS
def test_admin_cannot_reach_other_tenant(client):
for method in ("GET", "DELETE"):
r = client.request(method, "/v1/projects/proj_2",
headers=as_user("token_charlie"))
assert r.status_code == 404
assert "proj_2" in main.PROJECTS
def test_missing_token_gets_401_with_challenge(client):
r = client.get("/v1/projects/proj_1")
assert r.status_code == 401
assert r.headers["WWW-Authenticate"] == "Bearer"
# Permission matrix: (token, method, project, expected status)
MATRIX = [
(None, "GET", "proj_1", 401),
("not-a-token", "GET", "proj_1", 401),
("token_alice", "GET", "proj_1", 200), # member, own project
("token_alice", "GET", "proj_3", 404), # member, peer in tenant
("token_alice", "GET", "proj_2", 404), # member, other tenant
("token_alice", "DELETE", "proj_1", 403), # members cannot delete
("token_charlie", "GET", "proj_3", 200), # admin, own tenant
("token_charlie", "GET", "proj_2", 404), # admin, other tenant
("token_charlie", "DELETE", "proj_2", 404), # admin, other tenant
]
@pytest.mark.parametrize("token,method,project,expected", MATRIX)
def test_matrix(client, token, method, project, expected):
headers = as_user(token) if token else {}
r = client.request(method, f"/v1/projects/{project}", headers=headers)
assert r.status_code == expectedRun the suite from the auth-lab/ folder. As a negative check, the same tests run against a version without the tenant check and with a required header fail five cases: the cross-tenant admin cases and the missing-token cases.
$ python -m pytest -v --no-header
============================= test session starts ==============================
collecting ... collected 15 items
tests/test_authz.py::test_alice_can_read_own_project PASSED [ 6%]
tests/test_authz.py::test_alice_cannot_read_bobs_project PASSED [ 13%]
tests/test_authz.py::test_alice_cannot_delete_as_member PASSED [ 20%]
tests/test_authz.py::test_admin_can_delete_project_in_own_tenant PASSED [ 26%]
tests/test_authz.py::test_admin_cannot_reach_other_tenant PASSED [ 33%]
tests/test_authz.py::test_missing_token_gets_401_with_challenge PASSED [ 40%]
tests/test_authz.py::test_matrix[None-GET-proj_1-401] PASSED [ 46%]
tests/test_authz.py::test_matrix[not-a-token-GET-proj_1-401] PASSED [ 53%]
tests/test_authz.py::test_matrix[token_alice-GET-proj_1-200] PASSED [ 60%]
tests/test_authz.py::test_matrix[token_alice-GET-proj_3-404] PASSED [ 66%]
tests/test_authz.py::test_matrix[token_alice-GET-proj_2-404] PASSED [ 73%]
tests/test_authz.py::test_matrix[token_alice-DELETE-proj_1-403] PASSED [ 80%]
tests/test_authz.py::test_matrix[token_charlie-GET-proj_3-200] PASSED [ 86%]
tests/test_authz.py::test_matrix[token_charlie-GET-proj_2-404] PASSED [ 93%]
tests/test_authz.py::test_matrix[token_charlie-DELETE-proj_2-404] PASSED [100%]
============================== 15 passed in 2.75s ==============================What the named tests show:
- Cross-user and cross-tenant tests (
test_alice_cannot_read_bobs_project,test_admin_cannot_reach_other_tenant): Alice gets 404 for Bob's project, and so does Charlie, although he is an admin, because the project belongs to another tenant. An attacker cannot discover whether project IDproj_2exists. - Role boundary test (
test_alice_cannot_delete_as_member): Because Alice's role ismember,require_roles("admin")halts request execution with HTTP 403 Forbidden before the destructive route handler runs. - Administrative test (
test_admin_can_delete_project_in_own_tenant): Charlie, an admin, deletes another user's project in his own tenant. - Authentication test (
test_missing_token_gets_401_with_challenge): No header means 401 withWWW-Authenticate: Bearer, not 422.
With dozens of endpoints and roles, one hand-written test per permission combination is long to write and easy to leave gaps in. A permission matrix test lists every (caller, method, resource) case in one table and runs it with @pytest.mark.parametrize.
The MATRIX table above is such a test: each row is (token, method, project, expected_status), covering anonymous callers, members on their own, a peer's and another tenant's project, and admins inside and outside their tenant. When you add an endpoint or a role, add its rows; a reviewer can then read the whole access policy in one place.
06. Step 4: swap the mock tokens for signed JWTs
The SESSIONS dictionary stands in for a server-side session store: the token is an opaque random string, and the server looks it up on every request. Revoking it means deleting one entry. Many APIs use signed JWTs instead, checked without a lookup: the signature proves who issued the token, and the claims say who the caller is and until when. The price is that a JWT stays valid until its exp, so keep lifetimes short (the sessions and tokens lesson covers cookie flags, refresh rotation and revocation).
Because every route reaches the caller through get_current_user, you can change how callers authenticate without touching any authorization check. Install PyJWT (uv pip install "pyjwt==2.15.1") and save app/jwt_security.py. jwt.decode is told which algorithm to accept, rather than trusting the token's own alg header, and it must find exp, iss, aud and sub:
import os
from datetime import datetime, timedelta, timezone
import jwt
from fastapi import Header, HTTPException, status
from app.security import AuthenticatedUser
# Lab-only fallback; a real service reads the key from a secrets store
SECRET = os.environ.get("LAB_JWT_SECRET", "lab-only-not-a-real-secret-0123456789")
ISSUER, AUDIENCE = "https://auth.example.test", "projects-api"
def issue_token(user: AuthenticatedUser, minutes: int = 15, **override) -> str:
"""Sign a short-lived access token (the job of your login or auth server)."""
now = datetime.now(timezone.utc)
claims = {"sub": user.user_id, "tenant": user.tenant_id, "role": user.role,
"iss": ISSUER, "aud": AUDIENCE, "iat": now,
"exp": now + timedelta(minutes=minutes)}
return jwt.encode(claims | override, SECRET, algorithm="HS256")
async def get_current_user_jwt(
authorization: str | None = Header(default=None),
) -> AuthenticatedUser:
"""Same contract as get_current_user, but the token is a signed JWT."""
scheme, _, token = (authorization or "").partition(" ")
try:
if scheme.lower() != "bearer":
raise jwt.InvalidTokenError("no bearer token")
claims = jwt.decode(
token, SECRET, algorithms=["HS256"], # never trust the token's alg
audience=AUDIENCE, issuer=ISSUER,
options={"require": ["exp", "iss", "aud", "sub"]},
)
except jwt.InvalidTokenError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing, malformed or unknown bearer token",
headers={"WWW-Authenticate": 'Bearer error="invalid_token"'},
) from None
return AuthenticatedUser(claims["sub"], claims["tenant"], claims["role"])FastAPI's dependency_overrides replaces get_current_user everywhere, including inside require_roles and the ownership loader. Save check_jwt.py in auth-lab/ and predict each status code before you run python check_jwt.py. The last case is a token that claims role: admin with no signature at all (alg: none):
import jwt
from fastapi.testclient import TestClient
from app.jwt_security import get_current_user_jwt, issue_token
from app.main import app
from app.security import SESSIONS, get_current_user
# Every route depends on get_current_user: swap it, keep the authz checks
app.dependency_overrides[get_current_user] = get_current_user_jwt
client = TestClient(app)
alice = SESSIONS["token_alice"]
forged = jwt.encode({"sub": "usr_alice", "tenant": "tenant_a", "role": "admin"},
None, algorithm="none")
cases = [
("valid token, own project", issue_token(alice), "proj_1"),
("valid token, Bob's project", issue_token(alice), "proj_2"),
("expired a minute ago", issue_token(alice, minutes=-1), "proj_1"),
("token for another API", issue_token(alice, aud="billing-api"), "proj_1"),
("alg none, role admin", forged, "proj_1"),
]
for label, token, project in cases:
r = client.get(f"/v1/projects/{project}",
headers={"Authorization": f"Bearer {token}"})
print(f"{label}: {r.status_code}")valid token, own project: 200
valid token, Bob's project: 404
expired a minute ago: 401
token for another API: 401
alg none, role admin: 401A valid JWT still gets 404 for Bob's project: the token proves who Alice is, and the ownership loader still decides what she may see. The expired token, the token issued for another API (aud) and the unsigned token are all refused by jwt.decode before any route code runs. In production the key would come from a secrets store, or the API would verify tokens signed by an identity provider with its public keys, as the OAuth lesson shows.
07. Check your understanding
08. Apply it
Implement get_current_user, require_roles, and get_project_with_ownership in your FastAPI application. Write an automated pytest suite containing test cases for authorized access, cross-user forbidden access (expecting 404), and unauthenticated access (expecting 401).
Additionally, construct a comprehensive permission matrix test that exercises every role across every API route, so that a refactor that removes an ownership check or weakens an admin check fails a test.
With authorization in reusable dependency providers, your endpoints stay short, and a new route that forgets the ownership dependency stands out in review and in the matrix test.
This lab completes the skill: permission models, password hashing, sessions and tokens, OAuth 2.0 and OIDC, and ownership checks.
09. Review prompt
Explain how Broken Object Level Authorization (BOLA) occurs in REST APIs and how ownership dependencies prevent it. Describe why returning HTTP 404 is preferred over HTTP 403 for unauthorized resource lookups. Finally, explain how Depends() makes FastAPI run the authentication and role checks before the route handler, and why swapping get_current_user in step 4 left every authorization check unchanged.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.