In a FastAPI app, how does a get_current_user dependency turn a bearer JWT into a user, and where does get_current_active_user fit?
answer
- a dependency built on a dependency
- decode with a pinned algorithms list
- catch PyJWT's base exception
- sub names the user
- the active check sits on top
basics
~20 sget_current_user depends on the OAuth2PasswordBearer scheme, decodes the token with PyJWT's jwt.decode and a fixed algorithms list, reads sub, loads that user and raises 401 on any failure. get_current_active_user depends on it and rejects disabled accounts.
solid answer
~30 sThe chain has three links. The `OAuth2PasswordBearer` instance extracts the token string. `get_current_user` takes `token: Annotated[str, Depends(oauth2_scheme)]`, calls `jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])`, which checks the signature and `exp`, catches PyJWT's `InvalidTokenError`, reads the `sub` claim, loads that user and returns it; every failure raises the same 401 "Could not validate credentials" with `WWW-Authenticate: Bearer`. `get_current_active_user` depends on `get_current_user` and raises if the user is disabled (the docs use 400 "Inactive user"). Endpoints depend on the last link, often through an alias such as `CurrentUser = Annotated[User, Depends(get_current_active_user)]`, so the token handling is written once.
code
python · 63 linesfrom datetime import datetime, timedelta, timezone
from typing import Annotated
import jwt
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import InvalidTokenError
from pydantic import BaseModel
SECRET_KEY = "replace-with-a-secret-loaded-from-settings-32-bytes"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()
class User(BaseModel):
username: str
disabled: bool = False
USERS = {"ana": User(username="ana"), "bo": User(username="bo", disabled=True)}
def create_access_token(username: str) -> str:
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
return jwt.encode({"sub": username, "exp": expire}, SECRET_KEY, algorithm=ALGORITHM)
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except InvalidTokenError: # expired, malformed, bad signature, ...
raise credentials_exception
username = payload.get("sub")
if username is None:
raise credentials_exception
user = USERS.get(username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(
current_user: Annotated[User, Depends(get_current_user)],
) -> User:
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
CurrentUser = Annotated[User, Depends(get_current_active_user)]
@app.get("/users/me")
async def read_me(user: CurrentUser) -> User:
return usergo deeper
Recall that the endpoint asks for a user through Depends, and that a get_current_user dependency decodes the bearer token and loads that user.
Explain each link: the scheme, jwt.decode with a pinned algorithms list, the InvalidTokenError catch, the sub lookup, the active check, and which status each failure returns.
Review a chain for the failures that leak: uncaught decode errors becoming 500s, missing user reloads, secrets in source, distinct error messages per check.
Standardise one CurrentUser alias across services so identity has a single, testable implementation that can be swapped without touching endpoints.
## Why a chain of dependencies FastAPI's security story is built on its dependency system rather than on a separate auth layer. Instead of one function that does everything, the docs split the work into small dependencies, each declaring the one before it as a parameter. A path operation asks for the last link, and FastAPI resolves the whole chain for every request before the endpoint body runs. In the worked scenario, a mobile app signs in at `POST /token`, receives a JWT valid for 30 minutes, and calls `GET /users/me` with it. ## The chain, link by link 1. **The scheme.** `oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")` reads `Authorization: Bearer <token>` and returns the token string, or answers 401 "Not authenticated" if there is none. It validates nothing. 2. **`get_current_user`.** It declares `token: Annotated[str, Depends(oauth2_scheme)]` and turns the string into a user: - `jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])` verifies the signature with the server's key and, by default, rejects a token whose `exp` has passed. The `algorithms` list is fixed by the server, never read from the token. - `except InvalidTokenError` catches PyJWT's base class, which covers `ExpiredSignatureError`, `DecodeError` (a malformed or empty token) and a bad signature. - `payload.get("sub")` reads the subject; if it is missing the token is rejected. - The user is loaded from storage by that subject; if no such user exists, the token is rejected too. 3. **`get_current_active_user`.** It declares `current_user: Annotated[User, Depends(get_current_user)]` and raises when `current_user.disabled` is true. The docs answer with `HTTPException(status_code=400, detail="Inactive user")`. 4. **The endpoint** declares `Annotated[User, Depends(get_current_active_user)]` and receives a `User` object, never a token. ## What each failure returns | Failure | Raised by | Response | |---|---|---| | No `Authorization` header, or another scheme | the scheme | 401, "Not authenticated" | | Expired, malformed or badly signed token | `get_current_user` | 401, "Could not validate credentials" | | Token without `sub` | `get_current_user` | 401, "Could not validate credentials" | | `sub` names a user that no longer exists | `get_current_user` | 401, "Could not validate credentials" | | User exists but is disabled | `get_current_active_user` | 400, "Inactive user" (the docs' choice) | Each 401 carries `WWW-Authenticate: Bearer`, because the docs build one `credentials_exception` with that header and raise it from every branch. One message for every token failure is a sensible default: a client can do only one useful thing (sign in again), and distinct messages would tell a prober which check failed. ## Issuing the token the chain expects The token endpoint and the chain must agree. The docs' `create_access_token` copies the payload, adds `exp` as `datetime.now(timezone.utc) + timedelta(minutes=30)`, and signs with `jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)`; the login route passes `{"sub": user.username}`. The docs recommend `sub` hold an identifier unique across the whole application, and a string. Whatever goes into `sub` at login is exactly what `get_current_user` must look up later. The helper falls back to a 15-minute expiry when no `expires_delta` is passed; the login route passes `timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)`, 30 in the docs, so the lifetime is set in one constant rather than scattered across call sites. ## Why this shape pays off - **Written once.** Thousands of endpoints can declare a single `CurrentUser` alias; the decode logic lives in one place. - **Layered requirements.** "Any authenticated user" and "an active user" are separate dependencies, and an admin check can be a further link that depends on the active one. - **Run once per request.** If several dependencies in one request ask for `get_current_user`, FastAPI's per-request cache runs it once. - **Easy to replace in tests.** Overriding one dependency swaps the whole identity step. ## Mistakes reviewers catch - Catching only `ExpiredSignatureError`: a forged or malformed token then escapes as an unhandled exception and the client sees a 500. - Returning `None` instead of raising, so the endpoint runs with no user. - Trusting the token's claims as the user record without loading the account, so a deleted user keeps working until the token expires. - Loading the secret from source code; the docs' constant is a placeholder, and real keys come from settings. - Calling `jwt.decode` without `algorithms`: PyJWT refuses with a `DecodeError`, which surfaces as a 500 if uncaught.
- Why catch InvalidTokenError rather than ExpiredSignatureError in get_current_user?`InvalidTokenError` is the base class PyJWT raises from for every decode failure: expiry, a malformed or empty string, a bad signature. Catching only the expiry subclass lets the others escape the dependency, and FastAPI turns an unhandled exception into a 500 instead of the intended 401.
- The token is signed, so why does get_current_user still load the user from storage?A token outlives changes to the account. Loading the user turns a deleted account into a 401 at once, lets `get_current_active_user` see a fresh `disabled` flag, and gives the endpoint current data rather than claims frozen at sign-in time.
- Why do the FastAPI docs answer an inactive user with 400 rather than 401?The token is valid, so the caller is authenticated; a 401 would tell the client to sign in again, which cannot help. The docs pick 400 with "Inactive user". Many teams prefer 403 for a known account that may not proceed; the point is to keep it distinct from the token failures.
- Catching only ExpiredSignatureError, so a forged token surfaces as a 500
- Returning None from get_current_user instead of raising the 401
- Treating the decoded claims as the user record without loading the account
- Calling jwt.decode without an algorithms list and expecting it to work
- Decoding the token inside every path operation instead of one dependency