Dev.to Security 🔐 Cybersecurity 👁 0 📖 7 min read

JWT Security: 10 Mistakes We Keep Finding in API Audits

JWTs are not broken. The implementations around them are. These are the mistakes that turn a signed token into an open door — and how to test for each one. JSON Web Tokens are the default session mechanism for modern

JWTs are not broken. The implementations around them are. These are the mistakes that turn a signed token into an open door — and how to test for each one.

JSON Web Tokens are the default session mechanism for modern APIs. They are compact, stateless, and easy to integrate. They are also easy to use in a way that provides authentication without authorization, and integrity without revocation.

After enough API reviews, the same failure patterns show up again and again. Here are ten of them, with the test that exposes each one and the fix that removes it.

1. Accepting alg: none

The JWT header declares the signing algorithm:

{ "alg": "none", "typ": "JWT" }

Some libraries historically treated none as a valid algorithm, meaning "no signature required." An attacker could change the header to none, strip the signature, and set any claims they wanted.

Test: take a valid token, change alg to none, remove the signature, and send it. Try variations: None, NONE, nOnE.

Fix: explicitly allowlist the algorithms your service accepts (RS256, ES256, etc.) and reject everything else, including none. Never let the token header choose the verification method.

2. Not verifying the signature at all

A surprising number of services decode the JWT and read the claims without calling verify(). This happens when a developer uses a "decode" helper instead of a "verify" helper — the names are similar and the difference is easy to miss.

# Looks reasonable, verifies nothing
payload = jwt.decode(token, options={"verify_signature": False})

Test: change a claim (e.g. sub, role, tenant_id) without re-signing. If the API accepts it, the signature is not being checked.

Fix: always verify with the correct key and algorithm. Wrap verification in one function and make it the only way to read a token in your codebase.

3. Using a weak or shared secret

HMAC-signed JWTs (HS256) are only as strong as the secret. Common problems:

  • a short or guessable secret (secret, changeme, the app name),
  • the same secret across environments,
  • the secret committed to the repository,
  • the secret shared between services that should not be able to mint tokens for each other.

Test: check the secret length and entropy in configuration (not in the repo). Attempt offline cracking against a captured token with a wordlist — short secrets fall quickly. Look for the same secret in staging and production tokens.

Fix: use a long random secret from a secrets manager, rotate it, and scope signing keys per environment and per service. Prefer asymmetric keys (RS256/ES256) when multiple services need to verify but only one should sign.

4. Algorithm confusion (RS256 → HS256)

With asymmetric keys, the public key is used to verify and the private key to sign. Some libraries accept both algorithms. If the service expects RS256 but accepts HS256, an attacker can sign a token with HS256 using the public key as the HMAC secret — and the service will accept it.

Test: take the public key, create an HS256 token signed with it, and send it with alg: HS256. If accepted, the service is vulnerable.

Fix: allowlist exactly one algorithm family. Do not let the token header or a fallback path choose a different one.

5. Ignoring aud, iss, and exp

A signature proves the token was issued by someone with the key. It does not prove the token was meant for this service, from this issuer, and is still valid.

  • aud — the intended audience. A token for service A should not be accepted by service B.
  • iss — the issuer. Reject tokens from unknown issuers.
  • exp — expiration. Reject expired tokens.
  • nbf — not before. Reject tokens used too early.
  • iat — issued at. Useful for anomaly detection.

Test: remove exp, set it in the past, change aud to another service, change iss to a different value. Each should be rejected.

Fix: validate all registered claims explicitly. Most libraries do this only if you pass the expected values — check that you do.

6. Long-lived access tokens with no revocation

A JWT is valid until it expires. If access tokens live for days or weeks, a stolen token is usable for days or weeks. Logout does nothing to the token itself. Password changes do not invalidate it. Role changes do not take effect until it expires.

Test: log out, then replay the token. Change a user's role, then use the old token. Disable the user, then use the token. If any of these still work, revocation is missing.

Fix: short access-token lifetimes (minutes, not days) with refresh-token rotation. Maintain a server-side revocation list or token version per user, checked on refresh and on sensitive operations. For high-risk actions, require re-authentication.

7. Storing tokens in the wrong place

  • localStorage — readable by any JavaScript on the page, so any XSS becomes token theft.
  • sessionStorage — same exposure, shorter lifetime.
  • URLs — leak into logs, browser history, referrer headers, and analytics.
  • Non-HttpOnly cookies — readable by JavaScript.
  • Mobile app storage without encryption — extractable from backups or a rooted device.

Test: inspect where the token lives in the browser, whether it appears in URLs or logs, and whether it survives a logout. Check Set-Cookie flags: HttpOnly, Secure, SameSite.

Fix: store tokens in HttpOnly, Secure, SameSite cookies for browser clients, or in secure storage on mobile. Never put tokens in URLs. If you use cookies, add CSRF protection.

8. Trusting claims for authorization without server-side checks

{ "sub": "user_42", "role": "admin", "tenant_id": "acme" }

The service reads role and grants admin access. If the token is valid, the claim is treated as truth forever — even after the user is demoted, the tenant changes, or the role model evolves.

Test: change roles in the database and use an old token. Move a user to another tenant and use the old token. Check whether authorization uses the claim, the database, or both.

Fix: use claims for identity, not as the final authority for permissions. Re-check critical permissions server-side, especially for admin actions, billing, and cross-tenant access. Keep token lifetimes short so stale claims expire quickly.

9. Putting sensitive data in the payload

The JWT payload is signed, not encrypted. Anyone who holds the token can base64-decode it and read every claim. Embedding email addresses, internal IDs, roles, or personal data exposes them to anyone who intercepts the token.

Test: decode a token and read the payload. If you see PII, internal notes, or secrets, that is a finding.

Fix: keep claims minimal (sub, iss, aud, exp, iat, jti, maybe a tenant identifier). Put sensitive data behind an authenticated API call.

10. No binding to the client or context

A stolen bearer token is usable from anywhere. There is nothing tying it to the device, the session, or the original client.

Test: use a token from a different IP, user agent, or device. Check whether the service notices. Test concurrent use of the same token from multiple locations.

Fix: for high-value sessions, bind tokens to a device or session identifier, use sender-constrained tokens (mTLS, DPoP) where appropriate, and monitor for impossible-travel and concurrent-use anomalies. For most APIs, short lifetimes plus revocation plus anomaly detection are a pragmatic baseline.

Bonus: operational mistakes

  • No key rotation plan. A leaked signing key means every token is forgeable until the key changes. Have a kid header and a rotation process.
  • Keys in code or CI logs. Treat signing keys like any other secret.
  • No jti. Without a unique token ID, replay detection and revocation lists are harder.
  • Clock skew ignored. Strict exp validation without leeway causes false rejections; too much leeway extends the window.
  • Different validation in different services. One service verifies, another decodes. Standardize.

Where continuous testing fits

JWT mistakes are usually introduced by change, not by design: a library upgrade changes default verification, a new service decodes tokens without checking aud, a logout endpoint stops revoking, a token gets added to a URL for a quick integration. A one-time audit catches the state of the code on the day it runs.

LiveAPISec includes authentication checks in its OWASP API Top 10 core — weak JWT handling, algorithm confusion, tokens in URLs, refresh-token reuse, and logout replay are part of the deterministic test set. Running those checks continuously means a regression in token handling is caught on the deploy that introduced it, not in the next annual review.

pipx install liveapisec
liveapisec scan --help

A JWT test checklist

  • [ ] alg: none and algorithm variations are rejected.
  • [ ] Signature verification is always enabled.
  • [ ] The accepted algorithm is allowlisted, not chosen by the token.
  • [ ] The secret is long, random, environment-specific, and not in the repo.
  • [ ] Public-key confusion (RS256 → HS256) is not possible.
  • [ ] exp, nbf, aud, and iss are validated.
  • [ ] Logout, password change, role change, and user disable invalidate tokens.
  • [ ] Tokens are stored in HttpOnly/Secure/SameSite cookies or secure mobile storage.
  • [ ] Tokens never appear in URLs or logs.
  • [ ] Authorization re-checks critical permissions server-side.
  • [ ] The payload contains no PII or secrets.
  • [ ] Key rotation and kid are supported.
  • [ ] Anomalous token use is monitored.

Key takeaways

  • JWTs provide integrity, not confidentiality: the payload is readable.
  • A valid signature does not mean a valid session; check exp, aud, and iss.
  • Never let the token choose its own algorithm.
  • Short lifetimes plus revocation beat long-lived tokens with no exit.
  • Claims are identity, not a permanent permission grant.
  • Most JWT incidents are implementation mistakes, not cryptographic breaks.

Tags: JWT, API Security, Authentication, AppSec, Software Engineering

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.