Difficulty: Intermediate
How do you implement JWT-based authentication in FastAPI, from login to protecting routes?
In FastAPI, JWT auth is built from three pieces: a login endpoint that checks the password hash and issues a signed token, an OAuth2PasswordBearer security scheme that reads Authorization: Bearer <token> from requests, and a get_current_user dependency that verifies the token and loads the user. Any route that depends on get_current_user is protected, and the docs at /docs get an Authorize button automatically.
username and password as form data to /token (the OAuth2 password flow requires form fields, so install python-multipart).sub (user id), exp (expiry) and maybe role, signed with a secret key.{"access_token": "...", "token_type": "bearer"}.Authorization: Bearer <token> on later requests.get_current_user decodes the token, checks the signature and expiry, and fetches the user. Failure means 401 with a WWW-Authenticate: Bearer header.A JWT is header.payload.signature, each part base64url encoded. The signature proves the token was issued by someone with the key and was not modified. It does not encrypt anything: anyone can decode the payload, so never put passwords, PAN or Aadhaar numbers in it.
| Choice | Recommendation |
|---|---|
| Library | PyJWT (current FastAPI docs); python-jose is largely unmaintained |
| Password hashing | pwdlib with Argon2, or bcrypt; current docs moved away from passlib |
| Algorithm | HS256 for one service; RS256 or ES256 when other services verify tokens with a public key |
| Access token lifetime | Short, e.g. 15 to 30 minutes |
| Refresh token | Longer lived, stored server side or in an httpOnly cookie, rotated on use |
algorithms=["HS256"] to decode, or accepting none. Always pin the algorithm.datetime.utcnow(), which is deprecated since Python 3.12; use datetime.now(timezone.utc).SECRET_KEY in code. Load it from settings or a secrets manager.exp. For logout or a stolen token, keep tokens short and add a denylist (e.g. Redis keyed by jti) or a per-user token version.localStorage in a browser app exposes them to XSS; httpOnly cookies plus CSRF protection are safer for web frontends.Large Indian consumer apps typically use short-lived access tokens, rotating refresh tokens, and a central auth service (or a provider like Auth0, Keycloak or AWS Cognito). FastAPI services then only verify tokens using the provider's public keys (JWKS), so no shared secret is spread across microservices.
from datetime import datetime, timedelta, timezone
from typing import Annotated
import jwt # pip install pyjwt
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pwdlib import PasswordHash # pip install "pwdlib[argon2]"
SECRET_KEY = "load-from-env" # e.g. settings.jwt_secret
ALGORITHM = "HS256"
password_hash = PasswordHash.recommended()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
USERS = {"asha": {"username": "asha", "hashed": password_hash.hash("s3cret")}}
app = FastAPI()
def create_access_token(sub: str, minutes: int = 30) -> str:
exp = datetime.now(timezone.utc) + timedelta(minutes=minutes)
return jwt.encode({"sub": sub, "exp": exp}, SECRET_KEY, algorithm=ALGORITHM)
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> dict:
unauthorized = HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid credentials",
headers={"WWW-Authenticate": "Bearer"})
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) # checks exp too
except jwt.InvalidTokenError:
raise unauthorized
user = USERS.get(payload.get("sub"))
if user is None:
raise unauthorized
return user
@app.post("/token")
async def login(form: Annotated[OAuth2PasswordRequestForm, Depends()]):
user = USERS.get(form.username)
if not user or not password_hash.verify(form.password, user["hashed"]):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Wrong username or password")
return {"access_token": create_access_token(user["username"]), "token_type": "bearer"}
@app.get("/me")
async def read_me(user: Annotated[dict, Depends(get_current_user)]):
return {"username": user["username"]}
Login verifies a hashed password and issues a token with an expiry. get_current_user pins the algorithm, and PyJWT raises ExpiredSignatureError (a subclass of InvalidTokenError) for expired tokens.
OAuth2PasswordBearer, JWT, PyJWT, password hashing, access tokens