JWT Security Vulnerabilities: 6 Mistakes That Get Applications Breached in 2026
In 2022, researchers at PortSwigger documented an active exploitation pattern where attackers signed JWTs using a server's own public key under the HS256 algorithm, because the server failed to validate which algorithm it expected. Dozens of production APIs were vulnerable. JWT security vulnerabilities are among the most consistently exploited authentication flaws in modern applications, and six implementation mistakes account for the majority of real-world incidents.
The six mistakes below do not require sophisticated tooling to exploit. Each one has appeared in production incident reports within the last three years. None of them is difficult to fix once identified.
Mistake 1: Accepting the alg: none Algorithm
RFC 7518 lists "none" as a valid algorithm identifier for unsecured JWTs. Several JWT libraries treated the alg field in the token header as authoritative: if it said "alg": "none", the library skipped signature verification entirely. CVE-2015-9235 exposed this flaw in node-jsonwebtoken before version 4.2.2. Variants of the same logic appeared in Ruby, Python, and .NET libraries over the following years.
The attack is straightforward. An attacker takes a valid token, decodes the header, changes "alg": "HS256" to "alg": "none", modifies the payload claims (for example, setting "role": "admin"), strips the signature, and submits the result. A vulnerable library accepts it.
"Explicitly specify the expected signing algorithm when verifying tokens. Do not rely on the algorithm field within the token header to determine how to verify the signature." OWASP JSON Web Token Security Cheat Sheet
The fix is one line in most libraries:
# Vulnerable: trusts whatever algorithm the token claims
decoded = jwt.decode(token, SECRET, algorithms=jwt.get_unverified_header(token)['alg'])
# Fixed: server pins the expected algorithm
decoded = jwt.decode(token, SECRET, algorithms=["HS256"])
Never derive the algorithm from the token itself. Always hardcode it on the server.
Mistake 2: Weak or Predictable HS256 Secret
HS256 signs the token with a shared secret using HMAC-SHA256. If that secret is short or guessable, an attacker who captures a valid JWT can crack it offline. The token delivers the plaintext (header and payload) and the ciphertext (signature) together. An attacker needs only to test candidate secrets against the known content.
Hashcat mode 16500 targets JWTs directly. A 6-character alphanumeric secret falls in under 30 seconds on a single consumer GPU. A secret derived from an application name, environment variable default, or a dictionary word falls faster still. Common offenders in real incidents: secret, password, 1234567890, and environment names like development or staging.
Generate secrets with a cryptographically secure random number generator at a minimum of 256 bits (32 bytes). For anything beyond a single-service deployment, switch to RS256 or ES256. These use asymmetric key pairs: the private key signs; the public key verifies. An attacker who captures tokens and the public key still cannot forge new ones.
echo -n "your_jwt_secret" | wc -c on your current signing secret. If the result is below 32, rotate it immediately and update all token issuers.
Mistake 3: Storing JWTs in localStorage
LocalStorage is accessible to any JavaScript running on the same origin. A single stored XSS payload, injected via a user-supplied field that was not properly escaped, can read every token in localStorage and exfiltrate them in one HTTP request to an attacker-controlled server. The token is then valid for its full remaining lifetime regardless of where the original user is located.
The OWASP Top 10 (2021 edition) lists Injection as A03 and Insecure Design as A04. Both entry points feed into the localStorage theft pattern. High-profile bug bounty disclosures show localStorage token theft in the $5,000 to $30,000 payout range, indicating real-world exploitability across major platforms.
Prefer httpOnly cookies for token storage. An httpOnly cookie cannot be accessed by JavaScript at all. Even a successful XSS attack cannot read the token. Combine this with the Secure flag (HTTPS only) and SameSite=Strict to reduce cross-site request forgery exposure.
If localStorage is genuinely unavoidable (SPAs with cross-domain requirements being the most common case), implement a Content Security Policy that blocks all unknown script sources, apply output encoding at every render point, and rotate tokens frequently to limit the exploitation window.
Mistake 4: Skipping Claim Validation
JWT libraries verify the signature by default. They do not always validate claims by default. Developers who wire up token verification without explicitly enabling claim checks end up with tokens that behave in unexpected ways:
- Tokens that never expire because
expis not checked - Tokens accepted before their valid-from date because
nbfis not checked - Tokens accepted by any service in a multi-tenant system because
audis not checked - Tokens forged by a different issuer because
issis not checked
A concrete scenario that recurs in incident response reports: a JWT issued by a development environment is accepted in production because neither iss nor aud is validated. The dev token has permissive roles set for testing. Attackers who obtain a dev token (leaked via a public repository, for example) use it directly against the production API.
"Session secrets shall not be reused across different authentication contexts. Session tokens shall have defined and enforced lifetimes, and parties relying on tokens shall validate all relevant token metadata before granting access." NIST Special Publication 800-63B, Section 7.1 (Session Management)
Always validate exp, nbf, iss, and aud explicitly. Set a maximum token lifetime appropriate to the resource sensitivity: 15 minutes for financial APIs, 1 to 24 hours for standard user sessions. Use refresh tokens for silent renewal rather than extending access token lifetimes.
Mistake 5: Trusting the kid Header Without Sanitization
The kid (Key ID) header field tells the server which key to use when verifying the token. If the server uses the kid value to look up a signing key from a database or filesystem without sanitizing the input, an attacker who controls the token header can inject a SQL payload or a directory traversal string.
A SQL injection via kid looks like this:
# Malicious kid value in JWT header:
"kid": "' UNION SELECT 'attacker_secret' --"
# If the server runs this query unsanitized:
SELECT key FROM signing_keys WHERE kid = '...'
# The UNION clause substitutes the attacker's own value as the returned key
With the signing key now under attacker control, a forged token signed with attacker_secret passes signature verification. The attacker sets any claims they want in the payload.
A path traversal variant points kid at a predictable file on the server (for example, /dev/null on Unix systems), which returns an empty string. If the library treats an empty key as valid for a "alg": "none"-adjacent code path, the signature check is bypassed.
"If a server accepts the kid header value to locate a verification key without strict validation, an attacker can manipulate the key lookup to substitute a key of their choosing." PortSwigger Web Security Academy, JWT Attacks (2024)
The fix: maintain a whitelist of known, valid key identifiers in a map keyed by fixed strings. Reject any kid value not found in the whitelist before any database or filesystem operation runs.
Mistake 6: No Token Revocation Strategy
JWTs are stateless by design. The server does not track issued tokens. Once a token is valid, it remains valid until exp. This is the property that makes JWTs attractive for distributed systems. It is also the source of a class of problems that session-based authentication handles automatically.
Three scenarios make the absence of revocation costly:
- User logout. The token stays valid for its remaining lifetime. An attacker who captured it before logout can continue using it.
- Password reset after account takeover. Old tokens issued before the reset keep authorizing API calls. The attacker who triggered the reset keeps access.
- Role change. A user whose permissions are revoked continues to operate with old claims until the token expires.
Three mitigation patterns exist:
| Pattern | How it works | Trade-off |
|---|---|---|
| Short lifetime + refresh rotation | Access tokens expire in 15 min; refresh tokens issue new ones but are invalidated after single use | Minimal infrastructure; refresh endpoint becomes a target |
Token blocklist (jti claim) |
Store revoked token IDs in Redis; check on every request; prune after exp |
Reintroduces state; adds latency; Redis becomes a dependency |
| Token versioning | Store token_version on the user record; include it in JWT payload; increment to invalidate all tokens for that user |
Requires one DB lookup per request; no per-token granularity |
Short lifetime with refresh rotation is the most widely deployed pattern. It keeps the stateless property for access tokens while providing a revocation point at the refresh step.
Summary: Six Mistakes at a Glance
| Mistake | Root cause | Fix |
|---|---|---|
alg: none accepted |
Library trusts the token's own algorithm claim | Hardcode expected algorithm on the server; reject "none" |
| Weak HS256 secret | Short or dictionary-word signing secret | 32-byte CSPRNG secret; prefer RS256/ES256 for multi-service |
| JWT in localStorage | JavaScript-readable storage exposes token to XSS | httpOnly cookie with Secure and SameSite flags |
| Missing claim validation | Library default checks signature only | Explicitly validate exp, nbf, iss, and aud |
Unsanitized kid header |
Key lookup uses raw header value as input | Whitelist valid key IDs; reject unknown values before lookup |
| No revocation strategy | Stateless token design provides no invalidation | Short lifetime plus refresh rotation, or jti blocklist |
The Credential Layer Underneath
These server-side vulnerabilities combine with credential risk in a way that compounds exposure. A JWT stolen from localStorage is functionally equivalent to a stolen password for the duration of its validity: the attacker authenticates as the user without ever knowing the password. Password reuse makes this worse. A breach at any third-party service can hand attackers the username and password combination they then use to log in, generate a new token, and operate undetected.
Users who store unique, randomly generated credentials in a password manager like NordPass limit the blast radius of any single credential compromise. Each service gets a distinct password generated by a CSPRNG, so a breach at one site does not propagate. Combined with server-side JWT hardening, this closes both the token theft and the credential reuse vectors.
Frequently Asked Questions
What is a JWT?
A JSON Web Token is a self-contained, cryptographically signed credential that encodes user claims in a compact, URL-safe format. The three-part structure (header, payload, signature) allows stateless authentication: the server verifies the signature without querying a session store. JWTs are defined in RFC 7519 and are used in most REST APIs and single-page applications.
What is the most dangerous JWT vulnerability?
The alg: none bypass is the highest-severity flaw because it allows complete signature bypass without cracking a secret or stealing a private key. An attacker modifies the header, strips the signature, and submits a valid-looking token. CVE-2015-9235 exposed this in node-jsonwebtoken before version 4.2.2. All major libraries have mitigations now; the residual risk is in applications running outdated versions or failing to pin the expected algorithm on the verification call.
Should JWTs be stored in cookies or localStorage?
Cookies with the httpOnly flag are the safer choice. JavaScript cannot read httpOnly cookies, which blocks the most common XSS exfiltration path. LocalStorage is readable by any script on the page. If the application has an XSS vulnerability, tokens in localStorage are exposed immediately. Tokens in httpOnly cookies require a separate CSRF vector before an attacker can use them.
How long should a JWT access token be valid?
15 to 60 minutes covers most user-facing applications. Pair short-lived access tokens with refresh tokens that silently issue new access tokens when needed. Financial APIs typically use 5 to 15 minutes. Long-lived tokens of 24 hours or more are appropriate only for machine-to-machine calls where the token audience is locked to a specific service and refresh overhead is significant.