JWT (JSON Web Token) authentication is extremely common in modern APIs. With HMAC (HS256), the server uses a shared secret key to sign the token. Unlike RS256 (public/private keys), HS256 is simple and fast, making it ideal for microservices and internal APIs.
This tutorial walks through generating JWTs, validating them on each request, and securing protected routes.
FastAPI HS256 JWT Example
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from datetime import datetime, timedelta
import jwt
app = FastAPI()
security = HTTPBearer()
SECRET_KEY = "super-secret-hmac-key"
ALGORITHM = "HS256"
def create_jwt(username: str):
payload = {
"sub": username,
"exp": datetime.utcnow() + timedelta(hours=1),
"iat": datetime.utcnow()
}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
def verify_jwt(credentials: HTTPAuthorizationCredentials = Depends(security)):
token = credentials.credentials
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload["sub"]
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token")
@app.post("/login")
def login(username: str):
token = create_jwt(username)
return {"access_token": token}
@app.get("/secure-jwt")
def secure_route(username: str = Depends(verify_jwt)):
return {"message": f"Hello, {username}. JWT authentication successful."}Production Notes
1. Use a long, random SECRET_KEY
e.g., 256-bit value from a password generator.
2. Always set exp
Prevents unlimited-lifetime tokens.
3. Rotate keys periodically
Rolling secrets improves long-term security.
4. Never store sensitive data in JWT payloads
JWTs are Base64 encoded, not encrypted.
5. Prefer HTTPS
Always!!!
⸻
If you want, I can also create:
✅ Markdown files for each post
✅ SEO metadata (OpenGraph, Twitter Cards)
✅ Code-highlighted tutorial formatting
✅ A combined sitemap or index page for all posts
✅ ProxAuth-branded versions (to match your SaaS)
Just tell me!