Protecting Routes
Turn a login token into a real user on every request, then guard routes three ways: a whole router at once, by role, and by owner - with the owner check inside the SQL query. Plus two real leaks we found and fixed: a disabled user whose old token still worked, and a user who made himself admin through PATCH /me. And a ten-line test that lists every route left open by mistake.
What you will be able to do
- Build get_current_user that loads the user from the database on every request
- Use OAuth2PasswordBearer so /docs can log in for you
- Protect a whole router with one dependency
- Write a reusable role check with a dependency factory
- Check ownership inside the database query, and answer 404
- Stop old tokens and mass assignment from giving away access
- Test that no route is open by mistake
The idea, in plain English
Lesson 6.1 asked the two questions - who is calling, and may they do this - with fixed tokens in a dict. Now the tokens are real: a login gives a signed JWT (Lesson 6.3 explains how it is made), and every protected request sends it back as Authorization: Bearer <token>.
A token only says "this is user 2, until 15:30". It does not say whether user 2 still exists, is still active, or is still an admin. So get_current_user reads the user id from the token and loads the user from the database - every request. Everything else is built on that one dependency: a role check, an owner check, a whole protected router.
We build it on a to-do API with SQLite, attack it with an old token and a sneaky PATCH, and finish with a test that lists every unprotected route. FastAPI 0.143.0, SQLModel 0.0.50, PyJWT 2.15.1, pwdlib 0.3.1.
Worked example: A to-do API with ravi and mohan (users) and anu (admin): everyone sees only their own todos, only anu can see and disable users - attacked with an old token and a sneaky PATCH, then fixed.
1 - No token, or a bad one
get_current_user stops the request before your code runs.
Every protected request passes the same gates. Real results from our to-do API.
Words you will see in this lesson
A few new words, and two from Lesson 6.1.
Protected routeA route that answers only when the caller is logged in (and allowed).Current userThe user who sent this request, found from their token.JWTA signed token that carries a few facts, like a user id and an expiry time. Lesson 6.3.RoleA label that gives a group of rights - here "user" or "admin".OwnerThe user a row belongs to - here the owner_id of a todo.Mass assignmentCopying every field a client sends into the database - including ones they should never set.An everyday example: a hotel
- At check-in you show your ID once and get a key card - that is the login and the token.
- The card opens the main door and the lift - every floor checks it, like a protected router.
- It opens only YOUR room - the owner check. Room 214 does not tell you who is inside; it just stays shut (404).
- Staff cards open the store rooms too - a role.
- And when you check out, the hotel turns the card off at the front desk - the card itself still looks fine, but the system says no. That is why we look up the user every time.
Example 1 - the protected to-do API
pip install "fastapi[standard]" sqlmodel "pwdlib[argon2]" pyjwt, then read todos.py from top to bottom:
- Tables: User has a role and is_active. Todo has an owner_id.
- Models for clients: UserPublic and TodoPublic hide the hash and the owner. MeUpdate allows ONLY full_name, and forbids anything else.
- OAuth2PasswordBearer(tokenUrl="token") reads the Bearer token - like HTTPBearer in Lesson 6.1 - and also tells /docs where to log in.
- get_current_user: decode the token, load the user, check is_active. Every check in the API builds on it.
- require_role("admin") makes a dependency - a function version of the RequireRole class from Lesson 4.2. The same function gives require_role("admin", "editor") later.
- The todos router: dependencies=[Depends(get_current_user)] protects every route in it.
- get_own_todo finds a todo by id AND owner in one query - a dependency that read and delete both use.
- The admin router: one require_role("admin") for all its routes.
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from typing import Annotated
import jwt
from fastapi import APIRouter, Depends, FastAPI, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pwdlib import PasswordHash
from pydantic import ConfigDict
from sqlmodel import Field, Session, SQLModel, create_engine, select
SECRET_KEY = "45a1456a3ed0187fc7716d558f0c688c48e1e199e89a95b1264ce1f3317c6394" # secrets.token_hex(32)
password_hash = PasswordHash.recommended()
DUMMY_HASH = password_hash.hash("not-a-real-password")
engine = create_engine("sqlite:///todos.db")
# --- tables ---
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
username: str = Field(unique=True)
full_name: str = ""
hashed_password: str
role: str = "user" # "user" or "admin"
is_active: bool = True
class Todo(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
title: str
owner_id: int = Field(foreign_key="user.id", index=True)
# --- what clients may send and see ---
class UserPublic(SQLModel):
id: int
username: str
full_name: str
role: str
class MeUpdate(SQLModel): # only what a user may change about themselves
model_config = ConfigDict(extra="forbid") # "role": ... -> 422
full_name: str
class TodoCreate(SQLModel):
title: str
class TodoPublic(SQLModel):
id: int
title: str
def get_session():
with Session(engine) as session:
yield session
SessionDep = Annotated[Session, Depends(get_session)]
# --- login (Lesson 6.3 explains this part) ---
def create_token(user: User) -> str:
expires = datetime.now(timezone.utc) + timedelta(minutes=30)
return jwt.encode({"sub": str(user.id), "exp": expires}, SECRET_KEY, algorithm="HS256")
oauth2 = OAuth2PasswordBearer(tokenUrl="token") # reads "Authorization: Bearer <token>"
# --- authentication: WHO is calling? ---
def get_current_user(token: Annotated[str, Depends(oauth2)], session: SessionDep) -> User:
try:
user_id = int(jwt.decode(token, SECRET_KEY, algorithms=["HS256"])["sub"])
except (jwt.InvalidTokenError, KeyError, ValueError):
raise HTTPException(status_code=401, detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"})
user = session.get(User, user_id) # fresh from the database, every request
if user is None:
raise HTTPException(status_code=401, detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"})
if not user.is_active:
raise HTTPException(status_code=403, detail="Account disabled")
return user
CurrentUser = Annotated[User, Depends(get_current_user)]
# --- authorization: WHAT may they do? ---
def require_role(*roles: str):
def check(user: CurrentUser) -> User:
if user.role not in roles:
raise HTTPException(status_code=403, detail="Not allowed")
return user
return check
@asynccontextmanager
async def lifespan(app: FastAPI):
SQLModel.metadata.drop_all(engine) # a fresh demo database each start
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
for name, role in [("ravi", "user"), ("mohan", "user"), ("anu", "admin")]:
session.add(User(username=name, role=role,
hashed_password=password_hash.hash(f"{name}-pass-2026")))
session.commit()
session.add_all([Todo(title="Buy milk", owner_id=1), Todo(title="Pay rent", owner_id=2)])
session.commit()
yield
app = FastAPI(lifespan=lifespan)
@app.post("/token")
def login(form: Annotated[OAuth2PasswordRequestForm, Depends()], session: SessionDep):
user = session.exec(select(User).where(User.username == form.username)).first()
ok = password_hash.verify(form.password, user.hashed_password if user else DUMMY_HASH)
if user is None or not ok:
raise HTTPException(status_code=401, detail="Wrong username or password",
headers={"WWW-Authenticate": "Bearer"})
return {"access_token": create_token(user), "token_type": "bearer"}
# --- the user's own account ---
@app.get("/me", response_model=UserPublic)
def read_me(user: CurrentUser):
return user
@app.patch("/me", response_model=UserPublic)
def update_me(data: MeUpdate, user: CurrentUser, session: SessionDep):
user.sqlmodel_update(data.model_dump(exclude_unset=True))
session.add(user)
session.commit()
session.refresh(user)
return user
# --- todos: every route needs a user; each user sees only their own ---
todos = APIRouter(prefix="/todos", tags=["todos"], dependencies=[Depends(get_current_user)])
def get_own_todo(todo_id: int, user: CurrentUser, session: SessionDep) -> Todo:
todo = session.exec(
select(Todo).where(Todo.id == todo_id, Todo.owner_id == user.id) # the owner check is IN the query
).first()
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return todo
OwnTodo = Annotated[Todo, Depends(get_own_todo)]
@todos.get("", response_model=list[TodoPublic])
def list_todos(user: CurrentUser, session: SessionDep):
return session.exec(select(Todo).where(Todo.owner_id == user.id)).all()
@todos.post("", response_model=TodoPublic, status_code=201)
def create_todo(data: TodoCreate, user: CurrentUser, session: SessionDep):
todo = Todo(title=data.title, owner_id=user.id) # the owner comes from the token, never the body
session.add(todo)
session.commit()
session.refresh(todo)
return todo
@todos.get("/{todo_id}", response_model=TodoPublic)
def read_todo(todo: OwnTodo):
return todo
@todos.delete("/{todo_id}", status_code=204)
def delete_todo(todo: OwnTodo, session: SessionDep):
session.delete(todo)
session.commit()
# --- admin: the whole router needs the admin role ---
admin = APIRouter(prefix="/admin", tags=["admin"], dependencies=[Depends(require_role("admin"))])
@admin.get("/users", response_model=list[UserPublic])
def list_users(session: SessionDep):
return session.exec(select(User)).all()
@admin.post("/users/{user_id}/disable", response_model=UserPublic)
def disable_user(user_id: int, session: SessionDep):
user = session.get(User, user_id)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
user.is_active = False
session.add(user)
session.commit()
session.refresh(user)
return user
app.include_router(todos)
app.include_router(admin)from fastapi.testclient import TestClient
from todos import app
def login(c, name):
r = c.post("/token", data={"username": name, "password": f"{name}-pass-2026"})
return {"Authorization": f"Bearer {r.json()['access_token']}"}
with TestClient(app) as c:
ravi, mohan, anu = login(c, "ravi"), login(c, "mohan"), login(c, "anu")
for who, headers, method, url in [
("guest", {}, "GET", "/todos"),
("ravi", ravi, "GET", "/me"),
("ravi", ravi, "GET", "/todos"),
("ravi", ravi, "GET", "/todos/2"), # mohan's todo
("ravi", ravi, "DELETE", "/todos/2"),
("ravi", ravi, "GET", "/todos/99"), # does not exist
("ravi", ravi, "GET", "/admin/users"),
("mohan", mohan, "DELETE", "/todos/2"), # his own
("anu", anu, "GET", "/admin/users"),
]:
r = c.request(method, url, headers=headers)
print(f"{who:<6} {method:<6} {url:<13} -> {r.status_code} {r.text[:90]}")guest GET /todos -> 401 {"detail":"Not authenticated"}
ravi GET /me -> 200 {"id":1,"username":"ravi","full_name":"","role":"user"}
ravi GET /todos -> 200 [{"id":1,"title":"Buy milk"}]
ravi GET /todos/2 -> 404 {"detail":"Todo not found"}
ravi DELETE /todos/2 -> 404 {"detail":"Todo not found"}
ravi GET /todos/99 -> 404 {"detail":"Todo not found"}
ravi GET /admin/users -> 403 {"detail":"Not allowed"}
mohan DELETE /todos/2 -> 204
anu GET /admin/users -> 200 [{"id":1,"username":"ravi","full_name":"","role":"user"},{"id":2,"username":"mohan","full_Reading the output
- guest - 401 "Not authenticated". OAuth2PasswordBearer said it, before our code ran.
- ravi, GET /todos - only "Buy milk". The list is filtered in the query, so mohan’s todo never leaves the database.
- ravi, mohan’s todo (2) - 404, the same answer as for todo 99, which does not exist. ravi cannot even learn that todo 2 is there.
- ravi, DELETE mohan’s todo - also 404, and nothing deleted. read and delete share get_own_todo, so they cannot drift apart.
- ravi, /admin/users - 403: he is known, but not an admin.
- mohan deletes his own todo - 204. anu sees all users - 200.
Three ways to protect a route
All three use the same get_current_user. Choose by what the route needs:
A parameterThe route needs the user - to filter by owner, or to set the owner.The routerEvery route in a group needs a login or a role. New routes are protected too.The whole appRare - even /token and /docs would need a token. Lesson 4.4.Tip: The todos router protects every route AND list_todos asks for CurrentUser. FastAPI does not run get_current_user twice: within one request, a dependency is run once and its result reused (Lesson 4.2). We counted it below.
Counting: one user lookup per request
GET /todos/1 asks for get_current_user in two places - the router and get_own_todo. queries.py counts the SQL that reads the user table:
- One SELECT. FastAPI cached get_current_user for this request.
- So loading the user from the database costs one small query per request - not one per check.
from sqlalchemy import event
from fastapi.testclient import TestClient
from todos import app, engine
user_selects = 0
@event.listens_for(engine, "before_cursor_execute")
def count(conn, cursor, statement, *args):
global user_selects
if statement.startswith("SELECT") and "FROM user" in statement:
user_selects += 1
with TestClient(app) as c:
token = c.post("/token", data={"username": "ravi", "password": "ravi-pass-2026"}).json()["access_token"]
user_selects = 0
r = c.get("/todos/1", headers={"Authorization": f"Bearer {token}"})
print("GET /todos/1 ->", r.status_code)
print("get_current_user is needed by: the router, get_own_todo")
print("SELECT ... FROM user ran:", user_selects, "time(s)")GET /todos/1 -> 200
get_current_user is needed by: the router, get_own_todo
SELECT ... FROM user ran: 1 time(s)Owner checks: put them in the query
There are two ways to check an owner:
- Load, then compare: session.get(Todo, todo_id), then if todo.owner_id != user.id: 404. It works - but each route must remember to compare, and list routes cannot do it this way at all.
- In the query: select(Todo).where(Todo.id == todo_id, Todo.owner_id == user.id). Someone else’s todo is simply "not found". Lists use the same where().
- Put the query in ONE dependency (get_own_todo) and every route that uses it is safe, including routes you add next year.
- Answer 404, not 403, for other people’s data - 403 would tell ravi that todo 2 exists (Lesson 6.1).
- Admins who may see everything get their own routes, under /admin - not an "if admin" inside every user route.
Leak 1: a disabled user kept working
Our first version (todos_v1.py) put the role into the token and trusted the token alone - no database lookup. It is a popular shortcut: "the token is signed, so it must be right". leaks.py attacked both versions:
- Before: anu disabled mohan - and mohan’s old token still listed his todos (200). It would keep working until it expired, up to 30 minutes.
- The role in the token goes stale too: ravi’s token said "user" even after the database said "admin" (403 with the same token, 200 after a new login). So an admin you remove keeps admin rights until their token expires.
- The fix: put only the user id in the token, and load the user in get_current_user - is_active and role come from the database, every request.
- After: mohan’s old token gets 403 "Account disabled" at once.
- The cost is one small query per request - and we counted it above: one.
def create_token(user: User) -> str:
expires = datetime.now(timezone.utc) + timedelta(minutes=30)
return jwt.encode({"sub": str(user.id), "role": user.role, "exp": expires}, # role in the token
SECRET_KEY, algorithm="HS256")
def get_current_user(token: Annotated[str, Depends(oauth2)]) -> User:
try:
claims = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"})
return User(id=int(claims["sub"]), username="?", hashed_password="", # trusts the token,
role=claims["role"]) # no database lookupLeak 2: ravi made himself an admin
The first PATCH /me took any JSON object (data: dict) and copied it all into the user row with sqlmodel_update. ravi sent one extra field:
- Before: {"full_name": "Ravi K", "role": "admin"} answered 200 with "role":"admin". After a new login, ravi listed all users - 200.
- This is mass assignment. Nothing was wrong with the login or the tokens; the update simply accepted a field a user must never set.
- The fix: MeUpdate lists only full_name. With extra="forbid" (Lesson 1.6), "role" is a clear 422 instead of being silently dropped.
- After: 422 extra_forbidden, and ravi stays a user.
- The same rule for every model a client sends: never role, owner_id, is_active or id. Those come from the token, the URL, or an admin route.
@app.patch("/me", response_model=UserPublic)
def update_me(data: dict, user: CurrentUser, session: SessionDep): # any JSON object
user = session.get(User, user.id)
user.sqlmodel_update(data)
session.add(user)
session.commit()
session.refresh(user)
return userimport importlib
import sys
from fastapi.testclient import TestClient
app = importlib.import_module(sys.argv[1]).app
def login(c, name):
r = c.post("/token", data={"username": name, "password": f"{name}-pass-2026"})
return {"Authorization": f"Bearer {r.json()['access_token']}"}
def show(label, r):
print(f" {label:<38} -> {r.status_code} {r.text[:70]}")
with TestClient(app) as c:
print(sys.argv[1])
ravi, mohan, anu = login(c, "ravi"), login(c, "mohan"), login(c, "anu")
# Leak 1: anu disables mohan - does his old token still work?
show("anu disables mohan", c.post("/admin/users/2/disable", headers=anu))
show("mohan, old token: GET /todos", c.get("/todos", headers=mohan))
# Leak 2: ravi tries to make himself an admin
show("ravi PATCH /me with role=admin", c.patch("/me", headers=ravi,
json={"full_name": "Ravi K", "role": "admin"}))
show("ravi, same token: GET /admin/users", c.get("/admin/users", headers=ravi))
show("ravi logs in again: GET /admin/users", c.get("/admin/users", headers=login(c, "ravi")))todos_v1
anu disables mohan -> 200 {"id":2,"username":"mohan","full_name":"","role":"user"}
mohan, old token: GET /todos -> 200 [{"id":2,"title":"Pay rent"}]
ravi PATCH /me with role=admin -> 200 {"id":1,"username":"ravi","full_name":"Ravi K","role":"admin"}
ravi, same token: GET /admin/users -> 403 {"detail":"Not allowed"}
ravi logs in again: GET /admin/users -> 200 [{"id":1,"username":"ravi","full_name":"Ravi K","role":"admin"},{"id":
todos
anu disables mohan -> 200 {"id":2,"username":"mohan","full_name":"","role":"user"}
mohan, old token: GET /todos -> 403 {"detail":"Account disabled"}
ravi PATCH /me with role=admin -> 422 {"detail":[{"type":"extra_forbidden","loc":["body","role"],"msg":"Extr
ravi, same token: GET /admin/users -> 403 {"detail":"Not allowed"}
ravi logs in again: GET /admin/users -> 403 {"detail":"Not allowed"}A test that finds open routes
The most common hole is not clever - it is a new route where someone forgot the dependency. audit.py calls every route without a token and expects 401:
- It reads the routes from app.openapi()["paths"] - every route, routers included.
- Anything that is not 401 and is not on the PUBLIC list is printed as OPEN.
- Our app: everything protected. /token answers 422 without a body - it is public on purpose.
- Then we added a GET /stats to app and forgot the dependency. The audit caught it at once: 200, OPEN.
- Put this in your tests (Module 9), and a forgotten dependency fails the build instead of reaching users.
import re
from fastapi.testclient import TestClient
from todos import app
PUBLIC = {"/token"} # routes that are open on purpose
with TestClient(app) as c:
for path, operations in app.openapi()["paths"].items(): # every route, routers included
url = re.sub(r"\{\w+\}", "1", path) # /todos/{todo_id} -> /todos/1
for method in operations:
status = c.request(method.upper(), url).status_code # no token at all
if path in PUBLIC:
verdict = "public (on purpose)"
elif status == 401:
verdict = "protected"
else:
verdict = "OPEN - check this!"
print(f"{method.upper():<6} {path:<30} -> {status} {verdict}")POST /token -> 422 public (on purpose)
GET /me -> 401 protected
PATCH /me -> 401 protected
GET /todos -> 401 protected
POST /todos -> 401 protected
GET /todos/{todo_id} -> 401 protected
DELETE /todos/{todo_id} -> 401 protected
GET /admin/users -> 401 protected
POST /admin/users/{user_id}/disable -> 401 protectedPOST /admin/users/{user_id}/disable -> 401 protected
GET /stats -> 200 OPEN - check this!Watch out: Do not loop over app.routes for this. In FastAPI 0.143 the routes of an included router are not listed there one by one - our first audit saw only /token and /me, and missed six routes. The OpenAPI paths list all of them.
Logging in from /docs
- OAuth2PasswordBearer(tokenUrl="token") adds an "OAuth2, password" scheme to the OpenAPI schema.
- So the Authorize button in /docs now shows a username and password form. It calls POST /token for you and sends the token with every "Try it out".
- tokenUrl is relative: "token" means /token. It must match your login route.
- Lock icons appear on every route that needs the token - including all routes of the todos and admin routers.
{"OAuth2PasswordBearer": {"type": "oauth2", "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}}}A note on the secret key
- Our first key was a short phrase. PyJWT 2.15 warned: "The HMAC key is 23 bytes long, which is below the minimum recommended length of 32 bytes for SHA256".
- Make one with python -c "import secrets; print(secrets.token_hex(32))" - 64 characters.
- Anyone with this key can make tokens for any user, admin included. In this lesson it is in the code to keep the file short; Lesson 8.2 moves it to an environment variable.
Protecting routes at a glance
Read the token401 if missing; /docs gets a login form.
oauth2 = OAuth2PasswordBearer(tokenUrl="token")
Current userToken -> id -> user from the database -> active?
CurrentUser = Annotated[User, Depends(get_current_user)]
Needs a loginUse the user in the route.
def me(user: CurrentUser): ...
A role403 for other roles.
Depends(require_role("admin"))A whole routerEvery route in it, now and later.
APIRouter(dependencies=[Depends(get_current_user)])
Owner only404 for other people’s rows.
select(Todo).where(Todo.id == todo_id, Todo.owner_id == user.id)
Safe updatesOnly the fields a user may change.
class MeUpdate(SQLModel):
model_config = ConfigDict(extra="forbid")
full_name: strTry it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Run fastapi dev todos.py, click Authorize, log in as ravi / ravi-pass-2026, and try GET /todos and GET /admin/users. Then log out and in again as anu.”
“Paste an access_token into jwt.decode(token, options={"verify_signature": False}). What is inside? Is there a role?”
“Change the last character of ravi’s token and call /me. Which status and detail come back?”
“Remove dependencies=[...] from the todos router and run audit.py. Which routes turn OPEN - and which stay protected, and why?”
What usually goes wrong
It was true when the token was made. Disabled users and removed admins kept their rights until expiry. Load the user from the database.
✗ role = claims["role"]✓ user = session.get(User, int(claims["sub"]))
if not user.is_active: 403ravi sent "role": "admin" and became an admin. Use a model with only the allowed fields, and extra="forbid".
✗ def update_me(data: dict, ...): user.sqlmodel_update(data)✓ def update_me(data: MeUpdate, ...): user.sqlmodel_update(data.model_dump(exclude_unset=True))GET checks the owner, DELETE was written later and does not. Put the owner query in one dependency and use it everywhere.
The owner of a new todo is the current user - never a field the client sends.
✗ Todo(title=data.title, owner_id=data.owner_id)✓ Todo(title=data.title, owner_id=user.id)Protect routers instead of single routes, and keep a test like audit.py that fails on any open route.
Routes of included routers were missing from it. Use app.openapi()["paths"].
Best practices
- One get_current_user for the whole app; every check builds on it.
- Put only the user id (and expiry) in the token; read roles and status from the database.
- Protect routers, not single routes, and test that nothing is open by mistake.
- Filter by owner in the query, inside one shared dependency, and answer 404.
- Separate input models for each kind of update - never role, owner_id or is_active.
- Keep admin features under their own /admin router.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Add an "editor" role and a PUT /todos/{todo_id} that the owner may use - plus GET /admin/todos that lists ALL todos for admins and editors, but where only admins may disable users.
Show hintHide hint
require_role("admin", "editor") on the new route; the admin router keeps require_role("admin"). The owner PUT uses OwnTodo and a TodoUpdate model with only title.
Add POST /admin/users/{user_id}/enable. Then test the round trip: disable mohan, check his old token gives 403, enable him, check the SAME token works again. Why does it?
Show hintHide hint
The token never changed - only the row. Because get_current_user reads is_active every time, the answer follows the database.
Log out everywhere
Users want a "log out of all devices" button. A JWT cannot be taken back - but you look up the user on every request anyway.
- Add token_version: int = 0 to User, and put it in the token as "ver".
- get_current_user answers 401 when the token’s ver is not the user’s token_version.
- POST /me/logout-everywhere adds 1 to token_version.
- Show with TestClient: two tokens for ravi work, logout-everywhere, both give 401, a new login works.
Key points
- A token says who - get_current_user turns it into a real, active user from the database.
- OAuth2PasswordBearer reads the Bearer token and gives /docs a login form.
- dependencies=[...] on an APIRouter protects every route in it.
- require_role(...) is a dependency factory: one function, any roles.
- Owner checks belong in the query; other people’s rows are 404.
- Old tokens and mass assignment were the two real leaks - both fixed in a few lines.
- get_current_user ran once per request, however many dependencies needed it.
Quick check before you move on
Interview questions
How do you implement role-based access in FastAPI?
A single authentication dependency (OAuth2PasswordBearer plus token decode plus a database lookup with an active check), and authorization as composable dependencies on top - a role-check factory applied per route or per APIRouter, and resource ownership enforced in the query through a shared dependency, answering 404 to avoid leaking existence. Roles live in the database, not in long-lived tokens.
A JWT is stateless. How do you revoke access before it expires?
Keep access tokens short-lived and look up the user on each request (is_active, role); for logout-everywhere, store a token version or session id on the user and compare it with a claim in the token; for single tokens, a deny list of token ids (jti) until expiry. Refresh tokens are revoked server-side.
What is mass assignment and how do you prevent it?
Binding all client-supplied fields onto a model, letting clients set fields like role or owner. Prevent it with explicit input schemas per operation (only allowed fields, extra="forbid"), setting server-owned fields from the token or URL, and tests that try to set them.
Quiz
- 1.
Why load the user from the database when the token is signed?
- 2.
When do you add a dependency to a router instead of a route parameter?
- 3.
Why does require_role return a function?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...