← Back to FastAPI, page 2

fastapi-0040 · Hard senior

How do you implement fine-grained authorisation in FastAPI with OAuth2 scopes and Security()?

Declare scopes on OAuth2PasswordBearer(scopes={...}), put granted scopes in the token, and declare required scopes per endpoint with Security(get_current_user, scopes=["marks:write"]). Inside the dependency, SecurityScopes.scopes lists every scope required by the dependency chain, so one function checks them all and returns 401 or 403 with a proper WWW-Authenticate header. Scopes also appear in OpenAPI so /docs can request them.

Full answer

Role checks ("is admin?") get coarse quickly. OAuth2 scopes express permissions as strings such as marks:read, marks:write, fees:refund. A token carries the scopes granted to that user or client, and each endpoint states what it needs.

Pieces:

python
oauth2 = OAuth2PasswordBearer(tokenUrl="token",
                              scopes={"marks:read": "Read marks", "marks:write": "Edit marks"})

def get_current_user(security_scopes: SecurityScopes, token: str = Depends(oauth2)):
    payload = decode(token)
    granted = set(payload.get("scopes", []))
    missing = [s for s in security_scopes.scopes if s not in granted]
    if missing:
        raise HTTPException(403, "Not enough permissions",
                            headers={"WWW-Authenticate": f'Bearer scope="{security_scopes.scope_str}"'})
    return user

@app.put("/marks/{id}")
def edit(user = Security(get_current_user, scopes=["marks:write"])): ...

How it works:

  • Security() is Depends() plus scopes.
  • SecurityScopes collects scopes from the whole dependency chain. If a router requires marks:read and an endpoint adds marks:write, the dependency sees both.
  • Dependency caching is per set of scopes, so the same user dependency with different scopes is resolved separately.
  • OpenAPI lists scopes per operation; Swagger UI's Authorize dialog offers them.

Design advice:

  • Keep scopes about actions on resources, and map roles to scopes in one place at token creation (teacher gets marks:read marks:write).
  • Scopes say what kinds of action are allowed; they do not cover ownership. "Can edit marks" still needs "only for my classes", which belongs in the service or query layer (filter by teacher ID).
  • 401 for missing or invalid tokens, 403 for valid tokens without the scope.
  • If an identity provider issues tokens, read scopes from its claim (scope as a space-separated string in many providers, scp in some) and validate audience and issuer.
  • Libraries such as Casbin or Oso help when rules become complex (attribute-based access control).
python
from typing import Annotated

import jwt
from fastapi import Depends, FastAPI, HTTPException, Security
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
from fastapi.testclient import TestClient

KEY = "demo-only-signing-key-change-me-0123456789abcdef"
ROLE_SCOPES = {"student": ["marks:read"], "teacher": ["marks:read", "marks:write"]}
oauth2 = OAuth2PasswordBearer(tokenUrl="token", scopes={"marks:read": "Read marks", "marks:write": "Edit marks"})
app = FastAPI()


def make_token(user: str, role: str) -> str:
    return jwt.encode({"sub": user, "scopes": ROLE_SCOPES[role]}, KEY, algorithm="HS256")


def get_current_user(security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2)]):
    challenge = f'Bearer scope="{security_scopes.scope_str}"' if security_scopes.scopes else "Bearer"
    try:
        payload = jwt.decode(token, KEY, algorithms=["HS256"])
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token", headers={"WWW-Authenticate": challenge})
    missing = [s for s in security_scopes.scopes if s not in payload.get("scopes", [])]
    if missing:
        raise HTTPException(status_code=403, detail=f"Missing scope: {', '.join(missing)}",
                            headers={"WWW-Authenticate": challenge})
    return payload["sub"]


@app.get("/marks/{roll_no}")
def read_marks(roll_no: str, user: Annotated[str, Security(get_current_user, scopes=["marks:read"])]):
    return {"roll_no": roll_no, "maths": 81, "viewer": user}


@app.put("/marks/{roll_no}")
def edit_marks(roll_no: str, user: Annotated[str, Security(get_current_user, scopes=["marks:write"])]):
    return {"roll_no": roll_no, "updated_by": user}


c = TestClient(app)
student = {"Authorization": "Bearer " + make_token("aditi", "student")}
teacher = {"Authorization": "Bearer " + make_token("mr_paul", "teacher")}
print(c.get("/marks/BCA-17", headers=student).json())
r = c.put("/marks/BCA-17", headers=student)
print(r.status_code, r.json(), r.headers["www-authenticate"])
print(c.put("/marks/BCA-17", headers=teacher).json())
print(c.get("/marks/BCA-17", headers={"Authorization": "Bearer junk"}).status_code)
print(c.get("/openapi.json").json()["paths"]["/marks/{roll_no}"]["put"]["security"])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install pyjwt`. Tokens are created directly with demo roles to keep the example short. 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, PyJWT 2.15.1): {'roll_no': 'BCA-17', 'maths': 81, 'viewer': 'aditi'} 403 {'detail': 'Missing scope: marks:write'} Bearer scope="marks:write" {'roll_no': 'BCA-17', 'updated_by': 'mr_paul'} 401 [{'OAuth2PasswordBearer': ['marks:write']}]

Key points

  • Scopes are permission strings carried in the token
  • Security(dep, scopes=[...]) declares requirements per endpoint
  • SecurityScopes aggregates scopes across the chain
  • 401 for bad token, 403 for missing scope
  • Ownership checks still belong in services or queries

Common mistakes

  • Checking scopes in each endpoint body instead of one Security dependency
  • Returning 401 when the token is valid but lacks a scope
  • Treating scopes as ownership checks
  • Trusting scopes from a token without verifying signature, audience and issuer

Follow-ups

  • How would you restrict a teacher to editing marks only for their own classes?
  • How do scopes from a router and an endpoint combine?
  • When would you move to a policy engine such as Casbin or Oso?

Tips

  • Explain SecurityScopes aggregation
  • Separate scope checks from ownership checks
  • Get the 401 versus 403 distinction right