Authentication and JWT in FastAPI

Difficulty: Intermediate

Question

How do you implement JWT-based authentication in FastAPI, from login to protecting routes?

Answer

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.

The login flow step by step

  1. The client posts username and password as form data to /token (the OAuth2 password flow requires form fields, so install python-multipart).
  2. The server loads the user and verifies the password against a stored hash (Argon2 or bcrypt), never plain text.
  3. On success it creates a JWT with claims such as sub (user id), exp (expiry) and maybe role, signed with a secret key.
  4. It returns {"access_token": "...", "token_type": "bearer"}.
  5. The client sends Authorization: Bearer <token> on later requests.
  6. get_current_user decodes the token, checks the signature and expiry, and fetches the user. Failure means 401 with a WWW-Authenticate: Bearer header.

What a JWT actually guarantees

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.

ChoiceRecommendation
LibraryPyJWT (current FastAPI docs); python-jose is largely unmaintained
Password hashingpwdlib with Argon2, or bcrypt; current docs moved away from passlib
AlgorithmHS256 for one service; RS256 or ES256 when other services verify tokens with a public key
Access token lifetimeShort, e.g. 15 to 30 minutes
Refresh tokenLonger lived, stored server side or in an httpOnly cookie, rotated on use

Common mistakes

  • Not passing algorithms=["HS256"] to decode, or accepting none. Always pin the algorithm.
  • Using datetime.utcnow(), which is deprecated since Python 3.12; use datetime.now(timezone.utc).
  • Hardcoding SECRET_KEY in code. Load it from settings or a secrets manager.
  • Treating JWTs as revocable. A stateless token stays valid until 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.
  • Storing tokens in localStorage in a browser app exposes them to XSS; httpOnly cookies plus CSRF protection are safer for web frontends.

Production pattern

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.

JWT login and protected request. The token is issued once at login and then verified on every request.
  1. Client → FastAPI: POST /token with username, password
  2. FastAPI → Database: Load user and password hash
  3. Database → FastAPI: User row
  4. FastAPI → Client: Signed JWT access token
  5. Client → FastAPI: GET /me with Bearer token
  6. FastAPI → Client: Verified user data or 401

Code examples

JWT auth with PyJWT and pwdlib

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.

Key points

  • OAuth2PasswordBearer only extracts the bearer token; you verify it yourself
  • JWTs are signed, not encrypted: never put secrets in the payload
  • Always pin algorithms on decode and set a short exp
  • Hash passwords with Argon2 or bcrypt; current docs use PyJWT and pwdlib
  • Stateless tokens cannot be revoked without extra state like a denylist

Common follow-up questions

  • How would you implement refresh tokens and token rotation?
  • How do you log a user out when JWTs are stateless?
  • When would you choose RS256 over HS256?
  • Should a browser app store the token in localStorage or a cookie?

Interview tips

  • Walk through the flow end to end before showing code
  • Say clearly that JWT payloads are readable by anyone; many candidates get this wrong
  • Mention revocation and refresh tokens unprompted to show production awareness

Concepts covered

OAuth2PasswordBearer, JWT, PyJWT, password hashing, access tokens

More FastAPI Interview questions