Introduction
Every production API needs authentication. JWT (JSON Web Tokens) is the standard: stateless, scalable, and works across services. This post adds JWT auth to a FastAPI backend — login, token generation, protected routes, and refresh tokens.
Setup
pip install fastapi uvicorn python-jose[cryptography] passlib[bcrypt] python-multipart
Step 1: Password hashing
# auth.py
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
Never store plain passwords. Bcrypt is the standard for password hashing.
Step 2: JWT token creation
from datetime import datetime, timedelta
from jose import jwt, JWTError
SECRET_KEY = "your-secret-key-change-in-production" # use env var
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
REFRESH_TOKEN_EXPIRE_DAYS = 7
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
to_encode.update({"exp": expire, "type": "access"})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def create_refresh_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
to_encode.update({"exp": expire, "type": "refresh"})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def decode_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except JWTError:
return None
Step 3: User model and DB
# models.py
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String, unique=True, index=True)
hashed_password = Column(String)
role = Column(String, default="user")
Step 4: Auth dependency
# deps.py
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
payload = decode_token(token)
if payload is None or payload.get("type") != "access":
raise HTTPException(status_code=401, detail="Invalid or expired token")
username = payload.get("sub")
if username is None:
raise HTTPException(status_code=401, detail="Invalid token")
# Fetch user from DB
user = get_user_by_username(username)
if user is None:
raise HTTPException(status_code=401, detail="User not found")
return user
async def get_current_admin(user = Depends(get_current_user)):
if user.role != "admin":
raise HTTPException(status_code=403, detail="Admin only")
return user
Step 5: Login endpoint
# main.py
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()
@app.post("/token")
async def login(form: OAuth2PasswordRequestForm = Depends()):
user = get_user_by_username(form.username)
if not user or not verify_password(form.password, user.hashed_password):
raise HTTPException(status_code=401, detail="Invalid credentials")
access_token = create_access_token({"sub": user.username})
refresh_token = create_refresh_token({"sub": user.username})
return {
"access_token": access_token,
"refresh_token": refresh_token,
"token_type": "bearer",
}
Step 6: Protected routes
@app.get("/me")
async def get_me(current_user = Depends(get_current_user)):
return {"username": current_user.username, "role": current_user.role}
@app.get("/admin-only")
async def admin_panel(current_user = Depends(get_current_admin)):
return {"message": f"Welcome admin {current_user.username}"}
@app.get("/notes")
async def list_notes(current_user = Depends(get_current_user)):
return get_notes_for_user(current_user.id)
Step 7: Refresh token endpoint
@app.post("/token/refresh")
async def refresh_token(refresh_token: str):
payload = decode_token(refresh_token)
if payload is None or payload.get("type") != "refresh":
raise HTTPException(status_code=401, detail="Invalid refresh token")
username = payload.get("sub")
user = get_user_by_username(username)
if not user:
raise HTTPException(status_code=401, detail="User not found")
new_access = create_access_token({"sub": username})
return {"access_token": new_access, "token_type": "bearer"}
Step 8: Role-based access
from enum import Enum
class Role(str, Enum):
USER = "user"
ADMIN = "admin"
MODERATOR = "moderator"
def require_role(required: Role):
async def checker(current_user = Depends(get_current_user)):
if current_user.role != required.value:
raise HTTPException(status_code=403, detail=f"Requires {required.value} role")
return current_user
return checker
@app.delete("/users/{user_id}")
async def delete_user(user_id: int, current_user = Depends(require_role(Role.ADMIN))):
delete_user_by_id(user_id)
return {"deleted": user_id}
Step 9: Client usage (Python)
import requests
# Login
r = requests.post("http://localhost:8000/token",
data={"username": "admin", "password": "secret"})
tokens = r.json()
access_token = tokens["access_token"]
# Use token
headers = {"Authorization": f"Bearer {access_token}"}
r = requests.get("http://localhost:8000/me", headers=headers)
print(r.json()) # {"username": "admin", "role": "admin"}
# Refresh when expired
r = requests.post("http://localhost:8000/token/refresh",
json={"refresh_token": tokens["refresh_token"]})
new_access = r.json()["access_token"]
Step 10: Security best practices
- Use HTTPS in production — tokens in plain HTTP can be intercepted.
- Short access token expiry — 15-30 minutes. Refresh tokens last longer.
- Rotate refresh tokens — issue a new refresh token on each refresh (invalidate old).
- Store tokens securely — httpOnly cookies for web apps; secure storage for mobile.
- Use environment variables for
SECRET_KEY— never hardcode. - Add rate limiting — prevent brute-force login attempts.
- Log auth events — track failed logins, token refreshes.
Common mistakes
- Hardcoding SECRET_KEY — use env vars; rotate if leaked.
- Long access token expiry — if stolen, attacker has long access. Keep short (15-30 min).
- No refresh token rotation — refresh tokens should be single-use.
- Storing tokens in localStorage — XSS can steal them. Use httpOnly cookies.
- No rate limiting on login — brute-force vulnerability.
- Using symmetric keys for distributed systems — use RS256 (asymmetric) if multiple services verify tokens.
Key Concepts
- JWT = JSON Web Token (stateless auth)
- Access token = short-lived (15-30 min), used for API calls
- Refresh token = long-lived (7 days), used to get new access tokens
- OAuth2PasswordBearer = FastAPI’s token extraction
- Dependency injection =
Depends(get_current_user)for protected routes - RBAC = role-based access control
What to Try Next
- Add JWT to your Streamlit frontend.
- Implement OAuth (Google/GitHub) with
authlib. - Add Redis for token blacklisting (logout).
- Combine with FastAPI async SQLAlchemy for a full backend.
FAQ
JWT vs session-based auth?
JWT = stateless, scalable, works across services. Sessions = stateful, simpler, better for single apps. For APIs and microservices, JWT. For traditional web apps, sessions (with cookies) are simpler.
How do I revoke a JWT?
JWTs are stateless — you can’t revoke them directly. Solutions: (1) short expiry + refresh tokens, (2) token blacklisting in Redis, (3) use opaque tokens instead of JWTs for revocation needs.
RS256 vs HS256?
HS256 = symmetric (same key signs and verifies). RS256 = asymmetric (private key signs, public key verifies). Use HS256 for single-service apps; RS256 for distributed systems (multiple services verify without sharing the secret).