Guide
JWT security best practices
A JSON Web Token is only as safe as the code that checks it. These are the mistakes that have broken real authentication systems, what the standards say, and the few lines of configuration that prevent each one.
By Mark Stoumann ·
JWT best practices at a glance
- Verify, don’t just decode, and fix the allowed algorithms on the server.
- Sign with a strong key: 32 random bytes for HS256, or an asymmetric key.
- Check issuer, audience, expiry and token type on every request.
- Keep access tokens short-lived and refresh tokens revocable.
- Keep tokens out of
localStorage; prefer a backend that holds them. - Put identifiers in the payload, not personal data or secrets.
- Treat
kid,jkuandx5uas untrusted input.
Each one is explained below, with the attack it prevents.
Decoding is not verifying
Anyone can read a JWT. The header and payload are Base64url-encoded JSON, which is why the JWT decoder can show them without a key. What makes a token trustworthy is the signature, and the signature is only as good as the code that checks it. Many libraries have a decode() function next to verify(); using the first where you meant the second is the simplest way to accept a forged token.
The IETF wrote down the ways this goes wrong in RFC 8725, “JSON Web Token Best Current Practices”, published in 2020 after several years of library vulnerabilities. Most of this guide follows it.
1. Let the server pick the algorithm, not the token
The alg field in the header says how the token was signed. The trouble is that the attacker writes the header. Two classic attacks follow from trusting it:
- alg none. The JWT standard allows “unsecured” tokens with
"alg": "none"and an empty signature. An attacker edits the payload, setsnone, drops the signature, and a verifier that honors the header waves it through. Node’s popularjsonwebtokenpackage had a version of this as recently as CVE-2022-23540, fixed in version 9.0.0. - RS256 to HS256 key confusion. With RS256 the server verifies with a public key, which is often published. If the attacker changes the header to HS256, a naive verifier uses that same public key as an HMAC secret, and the attacker, who has the public key too, can sign anything. This was CVE-2015-9235 in
jsonwebtokenbefore 4.2.2, rated critical.
The fix for both is the same: tell the library which algorithms you accept, and tie each key to one algorithm.
// jsonwebtoken
jwt.verify(token, publicKey, {
algorithms: ['RS256'],
issuer: 'https://auth.example.com',
audience: 'api.example.com',
})
// jose
await jwtVerify(token, publicKey, {
algorithms: ['ES256'],
issuer: 'https://auth.example.com',
audience: 'api.example.com',
}) The jose library always rejects unsecured tokens, but without algorithms it still accepts every algorithm that fits the key. Write the list out anyway; it documents your intent and survives a library change.
2. Use a real key for HS256
HS256 signs with a shared secret. If that secret is a word like secret, changeme or your app’s name, an attacker who holds a single token can test guesses offline, as fast as their hardware computes HMACs, without ever touching your server. Once a guess produces the same signature, they can mint tokens for any user.
RFC 7518 requires an HS256 key of at least 256 bits, and RFC 8725 says a human-memorable password must never be used directly as the key. Generate one instead:
node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"Keep it in an environment variable or secret manager, never in the repository. And ask whether you need a shared secret at all: if more than one service verifies tokens, an asymmetric algorithm such as ES256 or RS256 lets them verify with a public key while only the issuer can sign.
3. Check who the token is from and who it is for
A valid signature only proves that someone with the key signed this token. It doesn’t prove the token was meant for your API. If one identity provider issues tokens for several services, a token for the low-risk reporting service could be replayed against the billing API unless the billing API checks the audience. RFC 7519 says a token whose aud doesn’t name the recipient must be rejected, and RFC 8725 makes the audience check mandatory when one issuer serves several apps.
| Claim | Check |
|---|---|
iss | Exactly your issuer, and the key used belongs to that issuer |
aud | Contains this service’s identifier |
exp | In the future, allowing at most a few minutes of clock skew |
nbf | In the past, with the same small leeway |
typ (header) | The type you expect, such as at+jwt for access tokens |
The last row stops a different kind of confusion: an ID token or a signed email-verification link being accepted as an access token because it happens to be signed with the same key. Giving each kind of token its own typ, and checking it, keeps them apart.
4. Keep access tokens short-lived
A JWT is self-contained: the server checks it without looking anything up. That is the whole point, and also the catch. There is no built-in way to revoke a token. If one leaks through a log file, a browser extension or a shared screenshot, it works until exp.
So keep the window small. A common pattern is an access token that lives for minutes and a refresh token that lives longer, is stored more carefully, and is checked against the server on every use, so it can be revoked when a user logs out or changes their password. If you truly need instant revocation of access tokens, you need a server-side lookup (a denylist of token IDs in jti), and at that point a plain session ID may be simpler.
Times in exp, iat and nbf are Unix timestamps in seconds. Passing Date.now(), which is in milliseconds, gives a token that expires tens of thousands of years from now. Paste a suspicious value into the timestamp converter to see what date it really is.
5. Be deliberate about where the browser keeps it
This is the most argued-about JWT question, and the standards are fairly clear. OWASP says not to keep session identifiers in localStorage, because every script on the page can read it, and one cross-site scripting flaw can send every token to an attacker. The IETF’s 2026 best practice for browser apps, RFC 10017, agrees that no browser storage can protect a token once an attacker runs code in your page.
| Where | Readable by injected scripts | Main risk |
|---|---|---|
| localStorage, sessionStorage | Yes | XSS steals the token itself, to use from anywhere |
| HttpOnly, Secure, SameSite cookie | No | Cross-site requests; use SameSite and CSRF protection |
| On a backend (BFF), browser gets a session cookie | No token in the browser at all | The backend becomes the thing to protect |
RFC 10017 strongly recommends the last option, a “backend for frontend”, for business apps, sensitive apps and anything handling personal data. An XSS attacker can still act through the victim’s open page, but can’t walk away with a token that keeps working after the tab closes.
6. Don’t put secrets in the payload
A signed JWT is not encrypted. Its payload is as readable as a URL parameter, and tokens end up in logs, error trackers and browser history. Keep claims to identifiers and permissions: a user ID, not an email address and date of birth; a role, not a list of every customer the user can see. If the contents must be confidential, the standard answer is an encrypted JWT (JWE), but most apps are better served by keeping the data on the server and the token small. The guide to hashing, encryption and encoding explains why Base64 hides nothing.
7. Treat kid, jku and x5u as untrusted input
The header can do more than name an algorithm. kid says which key signed the token, and jku and x5u point to a URL where the key can be fetched. All three are written by whoever made the token, so before the signature is checked they are just attacker-controlled strings. RFC 8725 names the two ways this goes wrong:
- Injection through
kid. If the key ID goes straight into a database query, a file path or an LDAP lookup, it is an injection point like any other form field. Look it up in a fixed map of your own keys, and reject IDs you don’t know. - Server-side request forgery through
jkuandx5u. A verifier that fetches whatever URL the header names can be made to call internal services, and to trust a key the attacker hosts. Configure your issuer’s key set URL yourself and ignore these headers, or accept only URLs on an exact allowlist.
Done that way, kid is also what makes key rotation painless: publish the new key next to the old one in your key set, start signing with it, and drop the old key once the last tokens it signed have expired. RFC 8725 asks for exactly this kind of cryptographic agility, so that a weak key or algorithm can be replaced without breaking every client.
A checklist for your verify call
verify(), neverdecode(), on anything you act on.- An explicit
algorithmslist, withoutnone. - One key per algorithm; an HS256 secret of 32 random bytes or more.
issuerandaudienceset, so they’re checked.- Clock tolerance of seconds or a few minutes, not hours.
- Access tokens that expire in minutes; revocable refresh tokens.
- No personal data in claims; no tokens in URLs.
- Keys looked up from your own list, never from a URL in the token.
Frequently asked questions
What are the most important JWT best practices?
Verify every token with an explicit list of allowed algorithms, never none. Use a strong key: 32 random bytes for HS256, or an asymmetric key such as ES256. Check issuer, audience, expiry and token type. Keep access tokens short-lived, treat kid and jku headers as untrusted input, keep personal data out of the payload, and keep tokens out of localStorage.
Is it safe to use JWTs for authentication?
Yes, if the server verifies every token properly: a fixed list of allowed algorithms, a strong key, and checks on issuer, audience and expiry. Most real JWT breaches come from verification code that trusts the token’s own header, not from the format itself.
What is the alg none attack?
The attacker changes the header to "alg": "none", removes the signature and edits the claims. A verifier that reads the algorithm from the token and accepts none will treat the forged token as valid. The fix is to pass your own list of allowed algorithms to the verify call and never include none.
How long should a JWT access token last?
As short as your app can live with, typically minutes rather than days, because a stolen token works until it expires and there is no built-in way to revoke it. Use a refresh token, stored more carefully and revocable on the server, to get new access tokens.
Should I store a JWT in localStorage or a cookie?
Neither is safe if an attacker can run JavaScript on your page. An HttpOnly, Secure, SameSite cookie at least keeps the token itself out of reach of scripts, while localStorage hands it to any script that runs. For sensitive apps, the IETF recommends keeping tokens on a backend and giving the browser only a session cookie.
How long should an HS256 secret be?
At least 256 bits, which is 32 random bytes. RFC 7518 requires a key at least as long as the hash output, and RFC 8725 forbids using a human-memorable password directly as the key. Generate it with a cryptographic random generator and keep it out of source control.