Cybersecurity

JWT Security: Eight Mistakes That Turn Tokens into Vulnerabilities

JSON Web Tokens are everywhere, and so are the ways they get misused. Learn what the IETF best-practice RFC says and how to secure your token handling.

By · Published · Updated · 5 min read

A glowing red padlock on a backlit keyboard

A JSON Web Token (JWT) is a compact, signed bundle of claims such as “this is user 42, an admin, valid until 3 p.m.”.[1] Your server can verify the signature without a database lookup, which is why JWTs are popular for APIs and single sign-on. It is also why mistakes are so costly: the token is the key.

The IETF published RFC 8725, “JSON Web Token Best Current Practices”, precisely because the same errors kept appearing across real implementations.[2] Here are the most important ones in plain language.

A quick anatomy lesson

A JWT has three Base64URL-encoded parts separated by dots: header (which algorithm), payload (the claims) and signature. Crucially, the payload is encoded, not encrypted. Anyone holding the token can read it. Never put secrets or sensitive personal data in a JWT payload.

Eight mistakes to avoid

  1. Accepting “alg: none” or trusting the header’s algorithm. Attackers have forged tokens by changing the algorithm field. Your server must decide which algorithm(s) are acceptable and reject everything else.[2]
  2. Mixing up HMAC and RSA keys. If a library lets the token choose between a symmetric and asymmetric algorithm, an attacker can sign with the public key as if it were an HMAC secret. Pin the algorithm per key.
  3. Not validating the claims. Always check exp (expiry), and verify iss (issuer) and aud (audience) so a token meant for one service cannot be replayed against another.[2]
  4. Weak signing secrets. Short or guessable HMAC secrets can be brute-forced offline. Use long, random keys from a secrets manager, or use asymmetric keys.[3]
  5. Long-lived access tokens. A stolen token works until it expires. Keep access tokens short (minutes) and use refresh tokens, which can be revoked.
  6. Storing tokens where scripts can steal them. Tokens in localStorage are readable by any injected script (XSS). Prefer HttpOnly, Secure, SameSite cookies where your architecture allows, which JavaScript cannot read.[4]
  7. No revocation plan. Stateless tokens are hard to cancel. Decide how you will handle logout, password changes and compromised accounts: short expiry, a deny-list of token IDs, or a per-user token version.
  8. Treating the token as authorisation. A valid signature proves identity, not permission. Still check on the server that this user may access this resource.

Verifying a token properly

import jwt from 'jsonwebtoken';

export function verifyAccessToken(token) {
  return jwt.verify(token, process.env.JWT_PUBLIC_KEY, {
    algorithms: ['RS256'],              // allow-list: never read this from the token
    issuer: 'https://auth.example.com', // who must have issued it
    audience: 'orders-api',             // who it must be intended for
    clockTolerance: 5,                  // seconds of allowed clock drift
  });
}

// In a route: identity from the token, permission from your own data.
router.get('/orders/:id', async (req, res) => {
  const claims = verifyAccessToken(getBearerToken(req));
  const order = await db.orders.findOne({ id: req.params.id, ownerId: claims.sub });
  if (!order) return res.status(404).json({ message: 'Not found' });
  res.json(order);
});

Do you even need JWTs?

For a conventional web app with one backend, a plain server-side session (an opaque random ID in a secure cookie, with the data stored on the server) is often simpler and safer. It can be revoked instantly and exposes nothing to the client.[4] JWTs shine when several independent services must verify identity without calling a central store, or when integrating with identity providers.

Where to keep tokens in the browser

Storage is a trade-off. Tokens kept in localStorage are readable by any script on the page, so a single cross-site scripting bug can leak them. Cookies marked HttpOnly cannot be read by JavaScript, which protects against theft through XSS, but cookies are sent automatically and so need protection against cross-site request forgery with SameSite settings and anti-CSRF tokens.

ApproachStrengthWeakness
HttpOnly, Secure, SameSite cookieNot readable by scriptsNeeds CSRF protection
localStorageSimple to implementExposed to any XSS
In-memory onlyHard to steal persistentlyLost on refresh; needs a refresh flow

A token lifecycle that holds up

  1. Issue a short-lived access token, for example 10 to 15 minutes.
  2. Pair it with a refresh token stored securely, rotated on each use, and revocable on the server.
  3. On logout, password change or suspected compromise, revoke the refresh token and any related sessions.
  4. Detect refresh-token reuse; if an old one is presented again, invalidate the whole family.
  5. Keep payloads small and free of sensitive data, because tokens are encoded, not encrypted.

Test your token handling like an attacker would

  • Change the algorithm in the header to none and confirm the server rejects it.
  • Alter a claim, such as the user ID or role, and confirm the signature check fails.
  • Present an expired token and a token meant for a different audience.
  • Try a token signed with a different key.
  • Replay a token after logout and confirm your revocation design works.

Choosing and configuring a library

Never write your own signing or verification code. Use a well-maintained library, keep it up to date, and read its security notes, because token libraries have had serious vulnerabilities in the past. When verifying, always specify the allowed algorithms explicitly, check the exp, iss and aud claims, and allow only a small clock-skew tolerance.

Store signing keys in a secrets manager or environment variable, never in the repository, and plan for key rotation. Include a key ID (kid) in the header so you can introduce a new key while old tokens remain valid until they expire. Practise a rotation before you need one in an emergency.

Frequently asked questions

Are JWTs bad?

No. They are a useful format when used for the right job, such as short-lived tokens between services. Problems arise when teams use them for long-lived browser sessions without a revocation plan. For many web apps, plain server-side sessions are simpler and safer.

HS256 or RS256?

HS256 uses one shared secret, so every service that verifies a token could also create one. RS256 uses a private key to sign and a public key to verify, which suits systems where many services only need to verify. Always pin the expected algorithm in your verification code.

Quick review checklist

  • Algorithm allow-list is hard-coded; “none” is rejected.
  • exp, iss and aud are verified on every request.
  • Signing keys are long, random and rotated; never committed to git.
  • Access tokens expire in minutes; refresh tokens are revocable.
  • Tokens are stored in HttpOnly cookies, or XSS risk is actively mitigated.
  • Payloads contain no sensitive data.
  • Authorisation is checked against your data, not just the token.

References & further reading

  1. IETF, RFC 7519: “JSON Web Token (JWT)”. https://www.rfc-editor.org/rfc/rfc7519
  2. IETF, RFC 8725: “JSON Web Token Best Current Practices”. https://www.rfc-editor.org/rfc/rfc8725
  3. OWASP Cheat Sheet Series, “REST Security Cheat Sheet” (includes guidance on JWTs and API authentication). https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html
  4. OWASP Cheat Sheet Series, “Session Management Cheat Sheet”. https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html