📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Cybersecurity and AI Security JWT Security

JWT Security

5 min read Quiz at the end
JWT pitfalls: alg:none bypass, weak secrets, missing validation, sensitive data exposure, no revocation.

JWT Security Deep Dive

# Common JWT vulnerabilities

# 1. Algorithm confusion attack (alg:none)
# Attacker changes header: {"alg":"none"}
# Forge any payload without signature!
# FIX: always specify expected algorithm
jwt.decode(token, secret, algorithms=["HS256"])  # whitelist only

# 2. Weak secret brute force
# FIX: use at least 256-bit random secret
import secrets
JWT_SECRET = secrets.token_hex(32)  # 256-bit random

# 3. JWT not validated on every request
# FIX: middleware validates every protected route
from functools import wraps
def require_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get("Authorization","").replace("Bearer ","")
        try:
            payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
            g.user_id = payload["sub"]
        except jwt.InvalidTokenError as e:
            return {"error": "Invalid token"}, 401
        return f(*args, **kwargs)
    return decorated

# 4. Sensitive data in JWT payload (base64 not encrypted!)
# NEVER put: passwords, SSN, credit cards in JWT

# 5. No token revocation for short-lived tokens
# FIX: access=15min, refresh=7days, blacklist on logout
Topic Quiz · 1 questions

Test your understanding before moving on

1. What is the JWT algorithm confusion vulnerability?
💡 The alg:none attack strips signature verification — always whitelist algorithms in jwt.decode().