Lesson 3 of 10
JWT Security
JWT (JSON Web Token) is widely used for stateless authentication and API authorization. However, JWT vulnerabilities are extremely common and can lead to complete authentication bypass, privilege escalation, and account takeover.
JWT Structure & How It Works
# JWT format: header.payload.signature
# Each part is Base64url encoded (NOT encrypted by default!)
# HEADER
{
"alg": "HS256", # Algorithm: HS256, RS256, ES256, none (!)
"typ": "JWT"
}
# PAYLOAD (claims) - readable by anyone!
{
"sub": "12345", # Subject (user ID)
"name": "Alice", # Custom claim
"role": "user", # Authorization claim - critical!
"iat": 1735689600, # Issued at
"exp": 1735776000 # Expiration time - ALWAYS set this
}
# SIGNATURE (integrity protection)
HMAC-SHA256(
base64url(header) + "." + base64url(payload),
secret_key
)
# Complete JWT:
# eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
# eyJzdWIiOiIxMjM0NSIsInJvbGUiOiJ1c2VyIn0.
# SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
# IMPORTANT: The payload is BASE64 ENCODED, not encrypted
# Anyone can decode it: base64 -d <<< "eyJzdWIiOiIxMjM0NSIsInJvbGUiOiJ1c2VyIn0="
# Output: {"sub":"12345","role":"user"}
# Never put sensitive data (SSN, credit card) in JWT payload!JWT Attack Techniques
import jwt
import json
import base64
# ATTACK 1: Algorithm Confusion - 'alg: none'
# Some libraries accept tokens with alg=none and no signature
# Attacker modifies payload (changes role to admin) and strips signature
original_token = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMiIsInJvbGUiOiJ1c2VyIn0.REAL_SIGNATURE"
header = {"alg": "none", "typ": "JWT"}
payload = {"sub": "12", "role": "admin"} # Elevated to admin!
forged = (
base64.urlsafe_b64encode(json.dumps(header).encode()).rstrip(b'=').decode() +
"." +
base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip(b'=').decode() +
"." # Empty signature
)
# ATTACK 2: RS256 to HS256 confusion attack
# RS256: signature uses RSA private key, verified with RSA public key
# HS256: signature uses HMAC with a shared secret
# Attack: if server accepts both, change alg to HS256 and sign with the PUBLIC key
# (public key is often available!) → signature validates!
# ATTACK 3: JWT Secret Brute Force
# Weak secrets (like "secret", "password", "jwt_secret") can be brute-forced
# Tools: hashcat, jwt_tool
# hashcat -a 0 -m 16500 <JWT> wordlist.txt
# SECURE IMPLEMENTATION:
import jwt as pyjwt
import os
from datetime import datetime, timedelta
SECRET = os.environ.get('JWT_SECRET') # Strong random secret
def create_token(user_id: int, role: str) -> str:
return pyjwt.encode(
{
"sub": str(user_id),
"role": role,
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(hours=1),
"jti": os.urandom(16).hex() # JWT ID - prevents replay attacks
},
SECRET,
algorithm="HS256" # EXPLICITLY specify algorithm
)
def verify_token(token: str) -> dict:
return pyjwt.decode(
token,
SECRET,
algorithms=["HS256"] # WHITELIST algorithms - reject alg: none
)JWT vs. Sessions - When to Use Each
- Sessions (server-side): Session ID stored in cookie, session data stored server-side (Redis/database). Easy to invalidate (delete session from store). Good for: traditional web apps, when you need instant revocation
- JWT (stateless): Token contains all state, verified by signature. Server stores nothing per-user. Hard to invalidate before expiry. Good for: microservices, APIs consumed by mobile/SPA, services that need to scale horizontally without shared state
- JWT revocation workaround: Maintain a token blacklist (Redis SET of jti values) - check on every request. Defeats statelessness but enables revocation
- Short expiry: Set JWT expiry to 15-60 minutes and issue a separate refresh token (stored server-side). On expiry, verify refresh token and issue new JWT. This limits the window of a stolen JWT
Common Mistakes
- Not validating algorithm (alg: none attack) - always explicitly whitelist allowed algorithms and reject all others
- Using a weak or guessable JWT secret - minimum 256 bits (32 random bytes) for HMAC; or use RS256 with 2048-bit RSA key
- Long JWT expiry (days/months) without refresh token mechanism - stolen JWTs are valid until expiry; keep expiry short (1 hour or less)
- Storing JWT in localStorage - localStorage is accessible to any JavaScript on the page; XSS can steal it. Use HttpOnly cookies for JWT storage when possible
Tip
Tip
Practice JWT Security in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of JWT Security from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with JWT Security is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- JWT (JSON Web Token) is widely used for stateless authentication and API authorization.
- Sessions (server-side): Session ID stored in cookie, session data stored server-side (Redis/database). Easy to invalidate (delete session from store). Good for: traditional web apps, when you need instant revocation
- JWT (stateless): Token contains all state, verified by signature. Server stores nothing per-user. Hard to invalidate before expiry. Good for: microservices, APIs consumed by mobile/SPA, services that need to scale horizontally without shared state
- JWT revocation workaround: Maintain a token blacklist (Redis SET of jti values) - check on every request. Defeats statelessness but enables revocation
Finished this lesson?