← Back to FastAPI, page 2

fastapi-0025 · Medium mid

How do you implement OAuth2 password flow with JWT access tokens in FastAPI?

Use OAuth2PasswordBearer(tokenUrl="token") to read the Bearer token, a /token endpoint that accepts OAuth2PasswordRequestForm, verifies the password hash (for example Argon2 via pwdlib) and returns a signed JWT with sub and exp claims, and a get_current_user dependency that decodes and verifies the token with PyJWT and loads the user. Keep access tokens short-lived, store the signing key in configuration, and return 401 with WWW-Authenticate: Bearer on failure.

Full answer

The pieces:

  1. Password storage: never store plain passwords. Hash with Argon2 or bcrypt. The current FastAPI docs use pwdlib with Argon2 (PasswordHash.recommended()); passlib is unmaintained.
  2. Token endpoint: POST /token with form fields username and password (the OAuth2 spec requires form data, which is why OAuth2PasswordRequestForm is used). On success, return {"access_token": ..., "token_type": "bearer"}.
  3. JWT creation: a JSON Web Token is a signed, base64-encoded JSON payload. Include sub (the user ID or username), exp (expiry), and optionally scopes or roles. Sign with HS256 and a secret from settings, or RS256/ES256 with a private key when other services must verify tokens with a public key.
  4. Protected routes: oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") reads Authorization: Bearer <token> and returns 401 if missing. get_current_user decodes with jwt.decode(token, key, algorithms=["HS256"]), which verifies the signature and exp, then loads the user and checks it is active.

Security details interviewers look for:

  • Always pass algorithms=[...] to decode; never accept the algorithm from the token header blindly.
  • JWTs are signed, not encrypted. Anyone can read the payload, so do not put secrets in it.
  • Short access token lifetime (5 to 30 minutes) plus refresh tokens stored securely (httpOnly cookie or server-side), rotated on use.
  • Revocation is hard with stateless tokens: keep lifetimes short, or keep a deny-list of token IDs (jti) in Redis for logout and password change.
  • Same error message for "no such user" and "wrong password", and run the hasher for unknown users too, to avoid user enumeration.
  • Rate limit /token.
  • OAuth2PasswordBearer adds an Authorize button in /docs.

For production, many teams use an identity provider (Keycloak, Auth0, Cognito, Entra ID) and only verify its tokens in FastAPI.

python
from datetime import datetime, timedelta, timezone
from typing import Annotated

import jwt
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.testclient import TestClient
from pwdlib import PasswordHash

SECRET_KEY = "demo-only-change-me-load-from-env-0123456789abcdef"   # from settings in real code
ALGORITHM = "HS256"
password_hash = PasswordHash.recommended()                         # Argon2
DUMMY_HASH = password_hash.hash("dummy")
USERS = {"meena": {"username": "meena", "hash": password_hash.hash("Canteen@12"), "active": True}}

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
CREDENTIALS_ERROR = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                                  detail="Could not validate credentials",
                                  headers={"WWW-Authenticate": "Bearer"})


def create_access_token(sub: str, minutes: int = 15) -> str:
    expire = datetime.now(timezone.utc) + timedelta(minutes=minutes)
    return jwt.encode({"sub": sub, "exp": expire}, SECRET_KEY, algorithm=ALGORITHM)


@app.post("/token")
def login(form: Annotated[OAuth2PasswordRequestForm, Depends()]):
    user = USERS.get(form.username)
    if not user:
        password_hash.verify(form.password, DUMMY_HASH)   # similar timing for unknown users
        raise HTTPException(status_code=401, detail="Incorrect username or password")
    if not password_hash.verify(form.password, user["hash"]):
        raise HTTPException(status_code=401, detail="Incorrect username or password")
    return {"access_token": create_access_token(user["username"]), "token_type": "bearer"}


def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except jwt.InvalidTokenError:
        raise CREDENTIALS_ERROR
    user = USERS.get(payload.get("sub"))
    if user is None or not user["active"]:
        raise CREDENTIALS_ERROR
    return user


@app.get("/me")
def me(user: Annotated[dict, Depends(get_current_user)]):
    return {"username": user["username"]}


c = TestClient(app)
print(c.post("/token", data={"username": "meena", "password": "wrong"}).json())
token = c.post("/token", data={"username": "meena", "password": "Canteen@12"}).json()["access_token"]
print(c.get("/me", headers={"Authorization": f"Bearer {token}"}).json())
print(c.get("/me").status_code)
expired = create_access_token("meena", minutes=-1)
r = c.get("/me", headers={"Authorization": f"Bearer {expired}"})
print(r.status_code, r.headers["www-authenticate"])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install pyjwt "pwdlib[argon2]" python-multipart`. The secret key is a demo value. 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, pwdlib 0.4.2): {'detail': 'Incorrect username or password'} {'username': 'meena'} 401 401 Bearer

Key points

  • Hash passwords with Argon2 or bcrypt (pwdlib)
  • /token accepts form data and returns a bearer JWT
  • JWT has sub and exp; decode with explicit algorithms
  • get_current_user dependency verifies and loads the user
  • Short-lived access tokens, refresh tokens, revocation strategy

Common mistakes

  • Storing plain or fast-hashed (MD5, SHA-256) passwords
  • Calling jwt.decode without the algorithms argument
  • Putting sensitive data in the JWT payload, which is only encoded
  • Issuing long-lived access tokens with no revocation plan
  • Different error messages for unknown user and wrong password

Follow-ups

  • How would you implement refresh tokens and rotation?
  • How do you log a user out when JWTs are stateless?
  • When would you use RS256 instead of HS256?

Tips

  • Name every piece: hashing, token endpoint, JWT claims, dependency
  • Mention explicit algorithms and short expiry
  • Discuss revocation, it separates mid from senior answers