JWT is everywhere — but a poorly implemented JWT is worse than none at all. ‘None’ algorithm, keys in code, tokens without expiration.
Secure creation¶
import jwt from datetime import datetime, timedelta def create_token(user_id, role): return jwt.encode({ ‘sub’: user_id, ‘role’: role, ‘iss’: ‘myapp’, ‘aud’: ‘myapp-api’, ‘exp’: datetime.utcnow() + timedelta(minutes=15), }, PRIVATE_KEY, algorithm=’RS256’) def verify_token(token): return jwt.decode(token, PUBLIC_KEY, algorithms=[‘RS256’], # Explicit algorithm! issuer=’myapp’, audience=’myapp-api’)
Common Mistakes¶
- alg: none — unsigned token accepted
- HS256 with shared secret
- Token without expiration
- Sensitive data in payload (JWT is not encrypted!)
- Token in localStorage (vulnerable to XSS)
Refresh token rotation¶
@app.post(‘/api/refresh’) async def refresh(request): old_refresh = request.cookies.get(‘refresh_token’) payload = verify_refresh_token(old_refresh) invalidate_refresh_token(old_refresh) # Rotation! new_access = create_access_token(payload[‘sub’]) new_refresh = create_refresh_token(payload[‘sub’]) response = JSONResponse({‘access_token’: new_access}) response.set_cookie(‘refresh_token’, new_refresh, httponly=True, secure=True, samesite=’strict’) return response
Key Takeaway¶
RS256, explicit algorithm, short expiration, refresh token rotation. JWT is a signature, not encryption.