Start With a Server-Side Session

If one application talks to its own server, an opaque session id with the state kept on the server is simpler, and it can be revoked at once. JWTs are for when several services have to verify a token themselves. That convenience has a price, and the rest of this article is about paying it properly.

Take a typical case, made up for illustration. A customer's account was used from another country for a full day. Nobody had their password. A browser extension had read the access token out of localStorage, and because that token was valid for 24 hours, the attacker simply kept using it. Nothing in the system could take it back.

A JWT used as an OAuth access token is a bearer token: whoever holds it is you, until it expires. (JWT is only a claims format, so that risk comes from how it's presented. Sender-constrained schemes like DPoP exist for that reason, and the readable three-part form below applies to signed JWTs, not encrypted ones.) Most JWT problems come from forgetting this. Long lifetimes, tokens readable by scripts, and services that check the signature but not who the token was issued for. Below is how the format works, the attacks that still land, and the validation rules every service should apply.

If your tokens live for days
  • Your token lifetime is 30 days “because logging in is annoying”
  • JWTs sit in localStorage where any XSS payload can grab them
  • You verify the signature but never check iss, aud, or exp
  • You have no way to revoke a token before it expires

The fix is short-lived access tokens, refresh tokens stored differently, and validating every standard claim — not just the signature.

Anatomy of a JWT

header.payload.signature
   │       │         │
   │       │         └── HMAC or RSA/ECDSA over (header || '.' || payload)
   │       └── claims: sub, iss, aud, exp, iat, nbf, jti, + your custom data
   └── { "alg": "RS256", "typ": "JWT", "kid": "2026-04" }

Everything before the second dot is readable by anyone. JWT is not encryption. If you need confidentiality, use JWE (or skip JWTs and use opaque session tokens with a server-side store).

HS256 vs RS256 / ES256

HS256 uses a shared secret for both signing and verifying — fine when one service issues and verifies its own tokens. The moment a second service needs to verify, you have to share the secret, and that's where it leaks. Use RS256 orES256 (asymmetric): the issuer signs with a private key, verifiers fetch the public key from JWKS, no secret distribution.

// Verifying an RS256 token with jose (the maintained JS library)
import { createRemoteJWKSet, jwtVerify } from 'jose';

const JWKS = createRemoteJWKSet(new URL('https://issuer.example/.well-known/jwks.json'));

const { payload } = await jwtVerify(token, JWKS, {
  issuer: 'https://issuer.example',     // pinning iss
  audience: 'urn:my-api',               // pinning aud — prevents token reuse across services
  algorithms: ['RS256'],                // EXPLICIT — blocks the 'none' attack
  clockTolerance: '30s',
});

The Classic JWT Attacks

The alg: none attack

Old libraries accepted { "alg": "none" } and skipped signature verification entirely. Always pass an explicitalgorithms allowlist to your verifier. Never trust the algorithm field in the header to drive a switch statement.

Algorithm confusion (RS256 → HS256)

Attacker takes your RS256 public key (it's public!), uses it as an HS256 secret, and forges tokens. Libraries that picked algorithm from the header were vulnerable. Again — explicit allowlist on the verifier side.

Key rotation without kid

Every token header should include a kid (key ID). Without it you can't rotate keys safely. JWKS endpoints publish multiple keys at once; the verifier picks by kid; you can publish a new key, switch issuance to it, and retire the old key once all tokens expire.


sequenceDiagram
    participant C as Client
    participant A as Auth Server
    participant API as API
    participant JWKS as JWKS endpoint
    C->>A: POST /token (creds)
    A-->>C: access_token (5m) + refresh_token (7d, rotating)
    C->>API: GET /resource (Bearer access_token)
    API->>JWKS: GET /.well-known/jwks.json (cached)
    JWKS-->>API: { keys: [{ kid, n, e }, ...] }
    API->>API: verify sig, iss, aud, exp, nbf
    API-->>C: 200
      
✅

Check it: Send your API a token whose header says the algorithm is none, and one signed with an algorithm you don’t use. Both should be rejected.

Access Tokens vs Refresh Tokens

Access tokens are short-lived (5–15 minutes) and sent on every request. Refresh tokens are long-lived (days), used once, and rotated on every exchange. Refresh-token rotation with reuse detection is the table-stakes defense against stolen tokens — if a refresh token is used twice, you invalidate the entire family and force re-auth.

✅

Check it: Decode one of your access tokens and work out its lifetime from the issued-at and expiry claims. Then use one refresh token twice. The second use should fail and end the session.

Where to Store Tokens

StorageProsCons
localStorageEasy, survives refreshAny XSS = full token theft
sessionStorageSame as above + tab-scopedSame XSS exposure
JS-readable cookieSent automaticallySame XSS exposure, plus CSRF
HttpOnly, Secure, SameSite cookieScripts can't read it, though injected code can still act as the user; CSRF mitigated by SameSite=LaxNeeds same-origin or careful CORS
In-memory onlyLost on refresh — refresh via cookieMost complex; safest for SPAs

For browser apps, the modern recommendation is: refresh token in an HttpOnly; Secure; SameSite=Strict cookie scoped to the auth endpoint, access token held in memory only. Mobile apps use the OS keychain.

✅

Check it: Open the browser console on your app and look in localStorage and document.cookie. A token you can read there can be read by any script on the page.

Revocation

JWTs are stateless — the server can't “invalidate” one without keeping state. Three pragmatic options:

  • Short lifetime + refresh rotation — the default. Compromise window = access-token lifetime.
  • JTI denylist — Redis set of revoked jtis, checked on every verify. Adds a hop but bounded by token TTL.
  • Per-user version claim — store a tokenVersion on the user; include it in the JWT; bump it on logout-all.

What to Validate on Every Request

// A strong default checklist. Exact required claims depend on your token profile.
1. Signature is valid with a key from your trusted set
2. alg matches your allowlist (never 'none')
3. exp is in the future (with small clock skew tolerance)
4. nbf and iat are reasonable
5. iss matches the expected issuer
6. aud contains your service identifier
7. sub is present
8. (Optional) jti is not in the revocation list
9. Scopes / roles match the route requirements, on every route that has them
✅

Check it: Take a valid token that was issued for a different audience and send it to your service. It should be refused.

Try It on Your Own System This Week

Three checks on an API you already run, about an hour in total:

  1. Find where the verifier gets its algorithm. It should come from your configuration, never from the token.
  2. Decode a production token and read the payload. Anything personal in it is visible to everyone who logs the token.
  3. Ask how you would cut off one compromised account right now. If the answer is to wait for expiry, know how long that is.

Pitfalls

Putting too much in the token

JWTs grow into every header and log line. Keep payloads small: sub, scopes, tenant, and an opaque user reference. Fetch the rest from your user store.

Trusting exp alone for security boundaries

Time-based expiry is necessary but not sufficient. For sensitive actions (password change, payment), require recent authentication regardless of token age (auth_time claim).

Forgetting that base64 is not encryption

Putting a user's email, phone, and role in the payload means anyone who logs the token sees them all. Treat the JWT payload as if it were printed on the side of a bus.

Revocation, and Tokens for Agents

The awkward truth about JWTs is that you can't easily take one back. A signed token stays valid until it expires, so a stolen 24-hour token gives an attacker 24 hours. Keep access tokens short, around 5 to 15 minutes, and let a refresh token do the long-lived work. For the rare cases when you must cut access immediately, such as a compromised account, keep a small denylist of token IDs (jti) in Redis with a TTL matching the token's expiry. That brings back a little state, and it's a sensible trade for the cases that need it.

Rotate refresh tokens on each use and detect reuse. If an old refresh token appears again, either the user or an attacker is replaying it, so revoke the whole token family. RFC 8725, the JWT best-practice document, is worth reading once: pin the accepted algorithm on the server, validate iss, aud and exp every time, and never let a token's own header choose how it gets verified.

Sender-constrained tokens

A bearer token works for whoever holds it. DPoP, RFC 9449, binds a token to a key held by the client, so a stolen token is useless without that key. It adds complexity, and it's worth considering for high-value APIs. The OAuth 2.0 Security Best Current Practice, RFC 9700, recommends sender-constraining for this reason.

Agents as token holders

AI agents have made token design more important. An agent carrying a user's long-lived token is a serious risk, because a prompt injection can turn that token against the user. OWASP's Agentic Top 10 lists this as ASI03, Identity and Privilege Abuse. So give an agent a short-lived token, with a narrow scope, for one task. Use token exchange (RFC 8693) so that the token records both the user and the agent acting for them. Your logs can then answer "who did this?", and "the user" alone is not a good enough answer once software acts on someone's behalf.

Never paste a token into a prompt or let one appear in a tool result. Anything in the model's context can end up in a log or a third-party service. Keep credentials outside the model, in the tool layer, where the model never sees them.