patternpythonCriticalpending
JWT authentication implementation checklist
Viewed 0 times
jwtaccess tokenrefresh tokenauthenticationhttponlycookie
Problem
Need to implement JWT-based authentication securely, avoiding common security pitfalls.
Solution
JWT implementation checklist:
Token creation:
Security checklist:
Token refresh flow:
Token creation:
import jwt
from datetime import datetime, timedelta
def create_tokens(user_id):
# Short-lived access token
access = jwt.encode({
'sub': str(user_id),
'type': 'access',
'iat': datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(minutes=15),
}, SECRET_KEY, algorithm='HS256')
# Long-lived refresh token
refresh = jwt.encode({
'sub': str(user_id),
'type': 'refresh',
'iat': datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(days=7),
'jti': str(uuid4()), # Unique ID for revocation
}, SECRET_KEY, algorithm='HS256')
return access, refreshSecurity checklist:
- Use short expiry for access tokens (5-15 min)
- Store refresh tokens in httpOnly cookies (not localStorage)
- Implement token rotation on refresh
- Maintain a blocklist for revoked refresh tokens
- Use RS256 (asymmetric) if multiple services verify tokens
- Never put sensitive data in payload (it's base64, not encrypted)
- Validate
iss,aud,expclaims on every request - Set
Secure,SameSite=Stricton auth cookies
Token refresh flow:
- Access token expires
- Client sends refresh token
- Server validates refresh token + checks blocklist
- Server issues new access + new refresh token
- Old refresh token is added to blocklist
Why
JWTs are stateless but that makes revocation hard. The access/refresh pattern limits the window of a compromised token while avoiding constant database lookups.
Gotchas
- JWTs in localStorage are vulnerable to XSS
- Algorithm confusion attacks: always specify algorithm on verification
- JWT payload is NOT encrypted, just signed
Context
Web applications implementing token-based authentication
Revisions (0)
No revisions yet.