--- title: "JWT Pitfalls: Where Token-Based Auth Goes Wrong" author: "Shobit Singh" published: "2026-11-19T11:22:23.605Z" updated: "2026-11-19T11:24:10.178Z" url: "https://zyvop.com/jwt-pitfalls-where-token-based-auth-goes-wrong-tawia" canonical: "https://zyvop.com/jwt-pitfalls-where-token-based-auth-goes-wrong-tawia" tags: ["OAuth","Web Security","authentication","jwt","node.js"] --- # JWT Pitfalls: Where Token-Based Auth Goes Wrong Where to store tokens, how long they should live, how to revoke them, and how algorithm confusion works, with Node.js examples for each pitfall. ![Cover image]() JSON Web Tokens are everywhere. A user logs in, gets a token, sends it with every request, and your API can verify who they are without touching a database. That convenience is real, but it comes with trade-offs that tutorials tend to skip. Most JWT security bugs aren't broken cryptography. They come from defaults and assumptions nobody questioned. This post covers four of the most common pitfalls: where you store the token, how long it lives, how you revoke it, and how your server decides which algorithm to trust. The examples use Node.js and the `jose` library. ## What you're actually working with A JWT has three base64url-encoded parts separated by dots: a header, a payload, and a signature. Decoded, the first two look like this: ```text Header: { "alg": "HS256", "typ": "JWT" } Payload: { "sub": "42", "role": "user", "iss": "https://api.example.com", "exp": 1798761600 } ``` Two facts explain most of the pitfalls below: - **A signed JWT is not encrypted.** Anyone holding the token can read the payload. The signature only proves it hasn't been tampered with. - **Verification is stateless.** The server checks the signature and claims without looking anything up. That's the main benefit, and it's also why revocation is hard. ## Pitfall 1: Storing the token in the wrong place Once the browser has a token, it has to keep it somewhere. Each option trades one risk for another. | Where | Readable by JavaScript? | CSRF risk? | Main downside | | --- | --- | --- | --- | | `localStorage` / `sessionStorage` | Yes | No | Any XSS bug can steal the token | | In memory (a JS variable) | Yes, by code on the page | No | Lost on page reload | | `HttpOnly` cookie | No | Yes, unless you add protection | Sent automatically with requests | `localStorage` is the most common choice because it's the easiest. It's also readable by every script on the page, so one XSS (cross-site scripting) bug, or one compromised third-party script, can send a user's token to an attacker. `HttpOnly` cookies can't be read by JavaScript at all. The catch is that browsers attach cookies automatically, which opens the door to CSRF (cross-site request forgery). `SameSite` settings and CSRF protection handle that. No option makes XSS harmless. With an `HttpOnly` cookie, injected script can't copy the token, but it can still make requests as the user while the page is open. What the cookie prevents is stealing the token to use later, somewhere else. A pattern that works well for many apps: 1. Keep a **short-lived access token in memory**. 2. Keep a **longer-lived refresh token in an** `HttpOnly`**,** `Secure`**,** `SameSite` **cookie**, limited to the refresh endpoint. 3. On page load, call the refresh endpoint to get a fresh access token. Here's how to set that cookie in Express: ```javascript res.cookie("refresh_token", refreshToken, { httpOnly: true, secure: true, sameSite: "strict", path: "/auth/refresh", maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days, in milliseconds }); ``` `SameSite=Strict` assumes your frontend and API share the same site. If they sit on different origins within one site, such as `app.example.com` and `api.example.com`, the fetch call needs `credentials: "include"` and your CORS setup must allow credentials. If they're on entirely different sites, you'll need a different setup and extra CSRF protection. ## Pitfall 2: Tokens that live too long A JWT stays valid until it expires, no matter what happens in the meantime. If someone steals one, they can use it for its entire lifetime. Two mistakes show up again and again: no `exp` claim at all, or an `exp` weeks or months away so users don't have to log in again. Keep access tokens short, typically 5 to 15 minutes. Handle the user experience with a refresh token instead: ```mermaid sequenceDiagram participant B as Browser participant A as API participant S as Auth server B->>A: Request with expired access token A-->>B: 401 Unauthorized B->>S: POST /auth/refresh (refresh cookie) S->>S: Check token, issue a new one, invalidate the old one S-->>B: New access token + new refresh cookie B->>A: Retry with new access token A-->>B: 200 OK ``` Refresh tokens are more valuable than access tokens, so treat them that way: - **Store them server-side**, hashed, so you can revoke them. - **Rotate them.** Every refresh returns a new refresh token and invalidates the old one. - **Detect reuse.** If an already-used refresh token shows up again, someone has a copy. Revoke the whole token family and force a new login. - **Allow for races.** Two tabs refreshing at the same moment can look like reuse. Many systems allow a short overlap window so people aren't logged out by accident. ### Verify, don't just decode A classic bug is calling `decode` when you meant `verify` (`jwt.decode` in `jsonwebtoken`, `decodeJwt` in `jose`). Decoding only reads the payload. It checks nothing. Here's how to sign and verify an access token with `jose`: ```javascript import { SignJWT, jwtVerify } from "jose"; import { randomUUID } from "node:crypto"; const secret = new TextEncoder().encode(process.env.JWT_SECRET); export function signAccessToken(userId, role) { return new SignJWT({ role }) .setProtectedHeader({ alg: "HS256" }) .setSubject(userId) .setIssuer("https://api.example.com") .setAudience("example-web") .setIssuedAt() .setExpirationTime("10m") .setJti(randomUUID()) .sign(secret); } export async function authenticate(token) { const { payload } = await jwtVerify(token, secret, { algorithms: ["HS256"], issuer: "https://api.example.com", audience: "example-web", requiredClaims: ["exp"], clockTolerance: 5, // seconds of leeway for clock drift }); return payload; } ``` Note `requiredClaims`. Without it, a token that has no `exp` at all can pass verification, and that token never expires. ## Pitfall 3: Assuming you can revoke a JWT Because a JWT is verified without a lookup, the server has no built-in way to say "that token is no longer good". If a user logs out, changes their password, or gets banned, their existing tokens keep working until they expire. The same goes for claims. If you put `role: "admin"` in a token and then demote the user, the old role sticks around until expiry. You have several options, each with a cost: | Approach | How it works | Trade-off | | --- | --- | --- | | Short expiry | Let tokens die quickly | Doesn't help inside the window; more refresh traffic | | Revoke refresh tokens | Store them server-side, delete on logout | The current access token still works until it expires | | Denylist | Store revoked token IDs (`jti`) until they expire | A lookup on every request | | Token version | Keep a `tokenVersion` per user, embed it in the token, bump it to invalidate | A lookup on every request, though it's easy to cache | | Server-side sessions | Skip JWTs for sessions | Needs a session store, but revocation is a delete | Here's a simple denylist with Redis. The entry expires on its own when the token would have: ```javascript // On logout: deny this token until it would have expired anyway const ttl = payload.exp - Math.floor(Date.now() / 1000); if (ttl > 0) { await redis.set(`revoked:${payload.jti}`, "1", { EX: ttl }); } // On every request, after verifying the token if (await redis.exists(`revoked:${payload.jti}`)) { throw new Error("Token revoked"); } ``` Notice what just happened: you added a lookup to every request. That's often a fine trade, and a Redis check is cheap, but you've reintroduced server-side state. For most apps, short-lived access tokens plus revocable refresh tokens cover the common cases. Add a denylist or version check for sensitive actions, or when "log out everywhere" has to take effect immediately. ## Pitfall 4: Algorithm confusion The JWT header includes an `alg` field that says how the token was signed. The catch is that the header is part of the token, and the token comes from the client. An attacker controls it. There are two classic attacks. **The** `none` **algorithm.** The spec defines `none` for unsigned tokens. Some libraries once treated those as valid, so anyone could forge any payload. Most libraries fixed this after the problem was disclosed in 2015, but old versions and hand-rolled code can still be affected. **RS256 to HS256 confusion.** With RS256, the server signs with a private key and verifies with a public key. The public key isn't secret. If the verifier trusts the `alg` in the header and uses one key variable for both cases, an attacker can switch the header to HS256 and sign the token using the public key as the HMAC secret: ```mermaid flowchart LR A["Attacker copies the server's public key"] --> B["Forges a token with header alg = HS256"] B --> C["Signs it using the public key as the HMAC secret"] C --> D["Vulnerable server: verifies with the public key and trusts the header alg"] D --> E["Forged token accepted"] C --> F["Safe server: algorithms pinned to RS256"] F --> G["Forged token rejected"] ``` The fix is to never let the token decide. Pin the allowed algorithms on the server: ```javascript import { importSPKI, jwtVerify } from "jose"; const publicKey = await importSPKI(process.env.JWT_PUBLIC_KEY_PEM, "RS256"); // Only RS256 is accepted, whatever the token header says const { payload } = await jwtVerify(token, publicKey, { algorithms: ["RS256"], issuer: "https://auth.example.com", audience: "example-api", }); ``` Many modern libraries also refuse to use a key of the wrong type for an algorithm. That's a useful safety net, but don't rely on it alone. The same rule applies to the rest of the header. Fields like `kid`, `jku`, and `jwk` can point your server at keys the attacker chose. Look up keys only from a list you control, and never fetch keys from a URL named in the token. ## More traps worth a quick check - **Sensitive data in the payload.** It's readable by anyone with the token. Keep emails, personal data, and secrets out of it. - **Missing** `iss` **and** `aud` **checks.** Without them, your API might accept a valid token that was issued for a different service. - **Weak HMAC secrets.** A short or guessable secret can be brute-forced offline once an attacker has any token. Use at least 32 random bytes, for example from `openssl rand -base64 32`. Fail at startup if the secret is missing. - **Tokens in URLs.** Query strings end up in logs, browser history, and referrer headers. Use the `Authorization` header or a cookie. - **Tokens in logs.** Redact `Authorization` headers and cookies in your logging setup. ## Do you need JWTs at all? If you have one web app talking to its own backend, a traditional server-side session in an `HttpOnly` cookie is often simpler and safer. Revocation is a delete, there's no algorithm to get wrong, and no token for JavaScript to hold. JWTs earn their place when several services need to verify tokens without sharing a session store, when you issue tokens to mobile apps or third parties, or when you're using OAuth 2.0 and OpenID Connect, where JWTs are part of the standard. OWASP's guidance points the same way: if your app doesn't need to be fully stateless, consider ordinary sessions. ## Checklist before you ship - Access tokens expire in minutes, and `exp` is required. - Refresh tokens are stored server-side, rotated, and checked for reuse. - Tokens aren't in `localStorage`. The refresh token lives in an `HttpOnly`, `Secure`, `SameSite` cookie. - Verification pins `algorithms` and checks `iss` and `aud`. - Nothing calls `decode` where it should call `verify`. - Secrets are long and random, kept in a secret manager, and rotatable. - The payload contains nothing sensitive. - You have a plan for logout, password changes, and role changes. - Tokens never appear in URLs or logs. ## Further reading - IETF, [RFC 8725: JSON Web Token Best Current Practices](). A catalog of known JWT threats and the recommended fixes. - Tim McLean, [Critical vulnerabilities in JSON Web Token libraries]() (2015). The classic write-up of the `none` and RS256/HS256 attacks, republished by Auth0. - OWASP, [JSON Web Token Cheat Sheet for Java](). Written for Java, but the issues around revocation and token theft apply to any stack. - Auth0 docs, [Refresh token rotation](). How rotation and automatic reuse detection work. - MDN, `Set-Cookie` [reference](). Details on `HttpOnly`, `Secure`, and `SameSite`. - `jose` [on GitHub](). The JavaScript library used in this post's examples.