Why "It Is Just Three Base64 Strings" Is Not Enough
Every JWT tutorial starts with the same picture:
That picture is correct. It is also dangerously incomplete.
The moment you ship it you face questions the tutorial never answered: Where do you store the token on the client? What happens when it is stolen? How do you log a user out if the server keeps no state? What if an attacker changes the header to alg: none? How do you add 2FA without issuing a full token too early? How do you rotate keys without logging everybody out?
A JWT is not an authentication system. It is a signed message format. The system around it (expiry, refresh, storage, verification rules, revocation) is what makes it safe or unsafe. This article walks through all of it, from the bytes of the token to the failure modes in production.
1. The Problem JWT Solves: Stateful vs Stateless
With classic server-side sessions, the server creates a random session ID at login, stores the session in memory or a database, and gives the ID to the client. Every request triggers a lookup. With a JWT, the server hands the client a signed token that already contains the identity. Any server holding the key can verify it without a lookup.
| Session | JWT | |
|---|---|---|
| Where state lives | Server (DB / Redis) | Inside the token, on the client |
| Per-request cost | Lookup | Signature verification (CPU only) |
| Horizontal scaling | Needs shared session store | Any instance with the key can verify |
| Instant revocation | Trivial: delete the session | Hard: token is valid until it expires |
| Best for | Server-rendered web apps | APIs, mobile apps, microservices, SSO |
Statelessness is a tradeoff, not a free win. You gain scalability and lose easy revocation. Everything in the rest of this article is about managing that tradeoff.
2. Anatomy of a JWT
A JWT is three Base64URL-encoded parts separated by dots:
| Part | Example | Purpose |
|---|---|---|
| Header | { "alg": "HS256", "typ": "JWT" } |
Declares the signing algorithm |
| Payload | { "sub": "user_123", "role": "admin", "iat": 1760000000, "exp": 1760000900 } |
The claims: data about the user and the token |
| Signature | HMACSHA256(base64url(header) + "." + base64url(payload), secret) |
Proves the token was not modified |
Encoded Is Not Encrypted
This is the most misunderstood fact about JWT. The header and payload are only Base64URL-encoded. Anyone who holds the token can read them (paste one into jwt.io and see). The signature gives you integrity (nobody can change the content without detection), not confidentiality (nobody can read it).
Never put passwords, national IDs, or any secret in a JWT payload. If you need confidentiality, use JWE (encrypted JWT) or keep the data on the server and put only an ID in the token.
3. Claims You Must Know
| Claim | Name | Meaning |
|---|---|---|
sub |
Subject | Who the token is about (usually the user ID) |
iss |
Issuer | Who created the token |
aud |
Audience | Which service the token is meant for |
exp |
Expiration | Unix time after which the token must be rejected |
iat |
Issued at | When the token was created |
nbf |
Not before | Token must not be accepted before this time |
jti |
JWT ID | Unique ID per token, useful for revocation and replay detection |
iss and aud matter more than people think. Without checking them, a token issued by one of your services for one purpose can be replayed against another service that trusts the same key.
4. Signing: HS256 vs RS256
| Algorithm | Keys | Who can create tokens | Who can verify | Best for |
|---|---|---|---|---|
| HS256 (HMAC) | One shared secret | Anyone with the secret | Anyone with the secret | Single service or tightly trusted services |
| RS256 (RSA) | Private + public key pair | Only the auth server (private key) | Anyone (public key) | Microservices, third parties, SSO |
| ES256 (ECDSA) | Private + public key pair | Only the auth server | Anyone | Same as RS256 with smaller keys and signatures |
With HS256, every service that can verify a token can also forge one. With asymmetric algorithms, the private key stays in one place and the public key can be distributed freely, usually through a JWKS endpoint that services fetch and cache.
Use a kid (key ID) header so you can publish several public keys at once. That is what makes key rotation possible without logging every user out.
5. The Basic Flow
Notice what the server does not do on request 5: no database lookup. That is the entire point. It is also the reason a stolen token works until it expires.
6. Access Tokens and Refresh Tokens
Because a JWT cannot be revoked easily, you make it short-lived. But a 15-minute token that forces a re-login every 15 minutes is unusable. The standard answer is two tokens:
| Access Token | Refresh Token | |
|---|---|---|
| Lifetime | Short: 5 to 15 minutes | Long: days or weeks |
| Sent to | Every API request | Only the /refresh endpoint |
| Stored on server | No | Yes, as a hash, so it can be revoked |
| If stolen | Limited damage window | Serious: attacker can mint new access tokens |
| Format | Usually JWT | JWT or opaque random string |
7. Refresh Token Rotation and Reuse Detection
A refresh token that never changes is a long-lived password sitting in the browser. Rotation fixes this: every time a refresh token is used, the server issues a new one and invalidates the old one. All tokens issued from one login form a family.
If R1 shows up a second time, either the legitimate user or an attacker has a stolen copy, and the server cannot tell which one. The safe response is to revoke the entire family and force a fresh login. The attacker loses access and the real user just logs in again.
8. Login With 2FA: The Temporary Token Pattern
When two-factor authentication is enabled, the password alone must not produce a full access token. Otherwise the second factor is decoration. The usual pattern is a two-step login with a short-lived, limited temporary token in between.
Rules for the temporary token:
- Very short expiry (a few minutes) and a dedicated claim such as
scope: "2fa"orpurpose: "2fa_pending". - Rejected by every normal endpoint. Your auth middleware must refuse a token whose scope is not the full-access scope.
- Single use if possible: store its
jtiand burn it after the code is verified. - Rate-limit the code attempts. A 6-digit code has only a million possibilities, so lock the flow after a few failures.
- TOTP codes change every 30 seconds. Allow at most one step of clock drift and reject a code that was already used.
9. Verifying a Token Correctly
Verification is more than "does the signature match". Every one of these checks exists because someone skipped it and got breached.
10. Where to Store Tokens on the Client
| Location | Advantage | Risk |
|---|---|---|
localStorage |
Simple, survives reloads | Any XSS can read and exfiltrate the token |
| In-memory variable | Not readable from storage by injected scripts | Lost on page refresh; needs a silent refresh |
httpOnly cookie |
JavaScript cannot read it | Sent automatically, so you need CSRF protection (SameSite, CSRF token) |
A widely used compromise: keep the access token in memory and the refresh token in an httpOnly, Secure, SameSite cookie scoped to the refresh path. On page load, call /refresh to get a new access token silently.
11. Attacks and Mitigations
| Attack | What Happens | Mitigation |
|---|---|---|
alg: none |
Attacker edits the header to say no signature is needed; a naive library accepts it | Always pass an explicit algorithm allow-list to verify |
| Algorithm confusion | Token switched from RS256 to HS256 and signed using the public key as the HMAC secret | Fix the expected algorithm per key; never derive it from the token |
| Weak secret | Short HS256 secret is brute-forced offline, then attacker forges any token | Random secret of 32+ bytes, or use asymmetric keys |
kid injection |
Unvalidated kid header used in a file path or SQL query |
Treat kid as an opaque lookup key into a fixed key set |
| Token theft (XSS) | Script reads the token from localStorage |
Memory storage, strict CSP, short expiry, httpOnly refresh cookie |
| CSRF | Browser auto-sends cookie to a forged request | SameSite cookies, CSRF tokens, custom header requirement |
| Token replay | Captured token reused until expiry | HTTPS only, short expiry, optional jti tracking for sensitive actions |
| Sensitive data in payload | Anyone holding the token can read it | Only IDs and roles in the payload |
Missing aud check |
Token for service A accepted by service B | Validate iss and aud on every service |
12. Logout and Revocation
"Stateless" and "revocable" pull in opposite directions. These are the practical options, from cheapest to strictest:
| Strategy | How It Works | Tradeoff |
|---|---|---|
| Short expiry only | Let access tokens die in 5 to 15 minutes | Simple; stolen token still works until expiry |
| Revoke refresh token | Delete the refresh token record on logout | Stops new access tokens; existing one lives out its TTL |
jti blacklist |
Store IDs of revoked tokens until they expire | Needs a fast store (Redis); adds a lookup per request |
| Token version | Keep token_version on the user row and in the token; bump to invalidate all |
One cheap read per request; kills all sessions at once |
| Key rotation | Remove the signing key | Nuclear option: invalidates every token |
Most systems combine the first two for normal logout and add a version counter for "log out everywhere" and password changes.
13. When Not to Use JWT
JWT is a good fit for APIs, mobile clients, microservices, and single sign-on. It is a poor fit for a classic server-rendered website where one server owns the session. There, a session cookie with a server-side store is simpler, revocable instantly, and has fewer ways to go wrong.
If you are using JWTs only to avoid writing a sessions table, and you then add a blacklist table, refresh table, and version counter to fix the gaps, you have rebuilt sessions with extra steps. Pick the tool that matches the problem.
14. Where JWT Auth Actually Breaks
| Failure Mode | What Happens | Mitigation |
|---|---|---|
| Forged token | Library accepts alg: none or a swapped algorithm |
Explicit algorithm allow-list; pin libraries; test with malformed tokens |
| Stolen access token | Attacker acts as the user until expiry | Short TTL; HTTPS; memory storage; strict CSP |
| Stolen refresh token | Attacker silently mints new access tokens for weeks | Rotation, reuse detection, family revocation, httpOnly cookie, device binding |
| Clock skew | Valid tokens rejected as expired or not yet valid across servers | NTP everywhere; small leeway (30 to 60 seconds) in verification |
| Key rotation outage | New key deployed before services fetch it; all requests fail | Publish new key in JWKS first, sign with it later, retire old key after max TTL |
| Oversized tokens | Too many claims exceed header size limits (often 8 KB) | Keep claims minimal; fetch permissions server-side |
| Stale permissions | User is demoted but their token still says admin | Short TTL; version check for sensitive operations |
| Refresh race | Two tabs refresh at once; second request looks like reuse and logs the user out | Single-flight refresh on the client; short grace window on the server |
| 2FA bypass | Temp token accepted by normal endpoints | Scope claim checked in middleware; temp token cannot call anything except 2FA verify |
| Brute-forced TOTP | Attacker guesses 6-digit codes | Rate limits, lockout, single-use codes |
15. Production Mindset
The core of JWT has not changed:
What the tutorials skip is the layer that makes it safe:
| Layer | What it does |
|---|---|
| Short-lived access tokens | Limit the damage window of any theft |
| Refresh tokens + rotation | Keep sessions long without long-lived bearer power |
| Reuse detection | Turns a stolen refresh token into a detectable event |
| Algorithm allow-list | Blocks none and algorithm-confusion attacks |
| iss / aud / scope checks | Stops tokens being replayed across services or purposes |
| Asymmetric keys + JWKS | Only one service can mint tokens; keys can rotate safely |
| Safe client storage | Reduces XSS and CSRF exposure |
| Temporary scoped tokens for 2FA | Keeps the second factor meaningful |
| Revocation strategy | Makes logout and password change actually work |
| Monitoring | Alerts on reuse events, signature failures, and refresh spikes |
None of these are optional hardening. Each one closes a hole that real systems have been breached through.
