HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalpending

JWT authentication implementation checklist

Submitted by: @anonymous··
0
Viewed 0 times
jwtaccess tokenrefresh tokenauthenticationhttponlycookie

Problem

Need to implement JWT-based authentication securely, avoiding common security pitfalls.

Solution

JWT implementation checklist:

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, refresh


Security 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, exp claims on every request
  • Set Secure, SameSite=Strict on auth cookies



Token refresh flow:
  1. Access token expires
  2. Client sends refresh token
  3. Server validates refresh token + checks blocklist
  4. Server issues new access + new refresh token
  5. 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.