The Analogy: A Conference Wristband Sealed Once at the Door
A multi-day conference runs one identity desk at the front entrance. The first time you arrive you hand over a passport; a staff member checks it against the registration list and, once satisfied, seals a tamper-evident wristband onto your wrist. From that moment on nobody looks at your passport again. Every session-room steward, every lunch line, every after-hours party simply glances at the band. The band, not you, has become the proof of who you are and what you are allowed into.
The band carries information anyone can read: your name, your tier printed in plain letters -- "attendee", "speaker", "organiser" -- and the date it stops being valid. It also carries a foil seal pressed by the front desk. The stewards trust the band not because the printing is secret -- it plainly is not, you can read your own band and so can the person next to you -- but because the seal is extremely hard to reproduce. Anyone can read the claims; only the desk can make them authoritative.
The seal is the whole point. Only the front desk owns the press that makes a valid seal, so a band with a broken seal, a missing seal, or a seal from some other event is refused at every door. A steward's check is therefore fast and self-contained: look at the seal, look at the printed expiry date, decide. No steward ever has to phone the front desk to ask "is this person really allowed?", which is exactly why the desk can close for the night and every interior door still works perfectly.
The trouble is that a sealed band cannot be un-issued. If your band is stolen, or you leave for good on the first afternoon, the band keeps opening doors until the printed expiry date arrives, because no steward is checking anything but the seal and the date. The venue has no live list of cancelled bands to cross-check, and building one would force every steward to call the desk on every glance -- destroying the speed the whole system was built for. The only workable defences are to print a short expiry so a lost band dies quickly, and to run a separate re-issue desk that you genuinely can shut off.
Syntax or Core Structure
A JSON Web Token is the wristband: three parts joined by dots -- header.payload.signature. The header and payload are each a JSON object encoded with base64url; the signature is the foil seal, produced by signing the first two parts with a secret only the server holds. Because the first two parts are merely encoded, not encrypted, anyone can decode and read them. The security comes entirely from the signature: change a single character of the payload and the seal no longer matches.
You issue a token after a successful password check and validate it on every later request. The code below builds a token, then a filter parses it: it splits on dots, verifies the signature against the pinned algorithm and key, checks the expiry, and only then trusts the claims.
String token = Jwts.builder()
.subject("alice")
.claim("role", "USER")
.issuedAt(Date.from(Instant.ofEpochSecond(1000)))
.expiration(Date.from(Instant.ofEpochSecond(1900)))
.signWith(key) // the seal: only this key makes it valid
.compact();
// on each request
Jws<Claims> jws = Jwts.parser()
.verifyWith(key) // reject any token not sealed by this key
.build()
.parseSignedClaims(token); // throws if signature or expiry fails
Claims claims = jws.getPayload(); // readable only AFTER the seal is checked
Decoding the token above -- splitting on the two dots and base64url-decoding the first two segments -- yields exactly the JSON that was put in. The signature segment is present but is never turned into human data; it exists only to be verified. The token was issued at second 1000 and expires at second 1900, so its lifetime is 900 seconds.
Output:
field value
--------------------------------------------------
segments 3
header (json) {"alg":"HS256","typ":"JWT"}
payload (json) {"sub":"alice","role":"USER","iat":1000,"exp":1900}
signature present (not decoded)
--------------------------------------------------
readable claims : 4
token lifetime : 900
The four readable claims -- sub, role, iat, exp -- are visible to anyone holding the token, which is the single most misunderstood fact about JWTs. A token is not a secret box; it is a sealed, legible card. Never place a password, a card number, or any other confidential value in a claim, because "encoded" is not "encrypted" and the base64url is trivially reversible.
Technical Depth: Password Storage Cost and Token Expiry
Passwords are stored as a slow, salted, one-way hash
Before any token is ever issued, the password must be checked, and how it is stored decides how bad a database leak is. The only acceptable shape is a slow, salted, one-way hash produced by a password-hashing function such as BCrypt, Argon2, or PBKDF2 -- never a fast general-purpose digest and never plaintext. The table names the schemes and the verdict for each.
| Storage choice | Speed | Salted | Verdict |
|---|---|---|---|
| Plain text | n/a | no | Catastrophic; a read-only leak is instant account takeover |
| MD5 or SHA-1 | very fast | no | Broken; billions of guesses per second, equal passwords equal hashes |
| SHA-256 | fast | no | Still fast, still wrong for passwords |
| BCrypt or Argon2 | deliberately slow | yes | Correct; salt and cost live inside the hash |
"Slow" is the feature, and BCrypt makes it a dial called the cost factor. The cost is a base-two exponent: work is 2^cost internal rounds, so raising the cost by one doubles the time an attacker spends per guess while barely troubling a single honest login. Because the cost and salt are stored inside the hash, you can raise the cost years later and existing users are upgraded on their next successful sign-in.
// each +1 to the cost doubles the rounds: rounds = 2^cost
int roundsAtCost(int cost) { return 1 << cost; } // 1<<10 = 1024, 1<<12 = 4096
Output:
cost rounds (2^cost) relative work
-------------------------------------
10 1024 1x
11 2048 2x
12 4096 4x
14 16384 16x
-------------------------------------
baseline cost : 10
each +1 doubles : yes
Expiry is checked against the clock, and the boundary is strict
Every access token carries an exp claim, and validation compares it to the current time. RFC 7519 is precise: the current time must be strictly before exp, so a token is accepted while now < exp and rejected the instant now reaches or passes it. The boundary matters -- at now == exp the token is already expired, not still valid. Fixing the clock at second 2000 and checking four tokens makes the rule concrete.
boolean valid(long now, long exp) { return now < exp; } // strict: equal means expired
Output:
token exp now < exp? state
-----------------------------------
t1 1900 no expired
t2 2000 no expired
t3 2500 yes valid
t4 3000 yes valid
-----------------------------------
fixed clock now : 2000
valid tokens : 2
expired tokens : 2
Token t2 expires exactly at the current instant and is rejected, which is why real deployments allow a small configurable clock-skew leeway (a few seconds) so that two servers whose clocks differ slightly do not reject each other's freshly issued tokens. The leeway is a deliberate, bounded relaxation of this strict boundary, not a licence to ignore expiry.
Real World Example: A Logout That Does Not Log Anyone Out
A team ships a stateless JWT API. Login issues a signed access token with a 900-second lifetime; every request is authorised purely by verifying the token's seal and expiry, with no server-side session and no record of which tokens exist. The product team then adds a "Log out" button. The implementation deletes the token from the browser's storage and calls it done -- and that is the whole bug, because deleting the client's copy does nothing to a token an attacker has already captured.
// the "logout" endpoint -- clears nothing the server knows about
@PostMapping("/logout")
public ResponseEntity<Void> logout() {
// there is no server-side state to clear; the token stays valid until exp
return ResponseEntity.noContent().build();
}
// every request is judged only by the token itself
boolean accept(long now, Claims c) {
return now < c.getExpiration().toEpochSecond(); // no revocation check at all
}
Suppose a token issued at second 1000 with expiry 1900 is captured, and the real user logs out at second 1200. The server keeps accepting the captured token on every request until it expires, because nothing in the request path knows the logout happened. The trace runs four requests after issue and counts how many the server still honours past the logout.
Output:
request t logout at t < exp (1900)? server accepts?
------------------------------------------------------
1300 1200 yes yes
1500 1200 yes yes
1800 1200 yes yes
2000 1200 no no
------------------------------------------------------
token exp : 1900
accepted after logout: 3
rejected (expired) : 1
Three requests are accepted after the user "logged out"; only the fourth fails, and it fails for expiry, not for logout. The design flaw is structural, not a typo: the system chose stateless tokens for their speed and horizontal scalability, and then bolted a logout feature onto them as if state existed. The two are in direct tension -- a token you can verify without asking a server is, by construction, a token you cannot revoke without asking a server.
The honest fixes all reintroduce exactly as much state as the security requires and no more. Make the access token short-lived -- a minute or two instead of fifteen -- so a leaked token dies quickly on its own, and pair it with a long-lived refresh token that is stored server-side and therefore can be deleted on logout or "sign out everywhere". If immediate revocation of access tokens is a hard requirement, keep a small server-side deny-list of token identifiers checked on each request, accepting that this trades away some of the statelessness that motivated JWTs in the first place. What you must not do is ship a logout button that quietly does nothing.
Common Mistakes
- Storing passwords with a fast or unsalted hash. MD5, SHA-1, and SHA-256 are built for speed, which is exactly wrong for passwords; an attacker tests billions per second, and without a per-password salt, identical passwords share a hash. Use BCrypt, Argon2, or PBKDF2 through a
PasswordEncoder.
- Comparing hashes yourself with
equals. BCrypt generates a fresh salt on every call, sostoredHash.equals(encoder.encode(raw))never matches, and a plainequalscan leak timing information. Always useencoder.matches(raw, storedHash), which extracts the salt and compares in constant time.
- Putting secrets in JWT claims. Claims are base64url-encoded, not encrypted, so anyone holding the token can read them. A password, card number, or other secret placed in a claim is effectively published to every client that receives the token.
- Trusting claims before verifying the signature. Parsing a token in a mode that skips verification, or reading the payload before the seal is checked, lets an attacker forge any identity. Verify the signature first; only then read the claims.
- Letting the token choose its own algorithm. Honouring the
algvalue from the token's own header enables algorithm-confusion attacks, including the notoriousnonealgorithm. Pin the expected algorithm and key on the server side.
- Forgetting to check expiry. Some parsers verify the signature but will not reject an expired token unless explicitly asked. A token with a valid seal but a past
expmust still be refused; the boundary is strict, with only a small deliberate clock-skew leeway.
- Believing a client-side logout revokes the token. Deleting the token from browser storage does nothing to a copy an attacker already holds; a stateless token stays valid until
exp. Real logout requires a server-side refresh token to delete or a short access-token lifetime.
- Issuing long-lived access tokens. A fifteen-minute or multi-hour access token is a fifteen-minute or multi-hour window for a stolen token. Keep access tokens short and lean on a revocable refresh token for longevity.
- Revealing whether an account exists. Returning "no account for that email" on a failed login turns the form into an account-enumeration oracle. Return one generic message and status for both unknown-user and wrong-password, and log the specific reason only server-side.
Best Practices
- Store passwords only through a
PasswordEncoderbacked by BCrypt or Argon2, and verify withmatchesrather than comparing strings yourself.
- Set the BCrypt cost so a single hash takes a noticeable fraction of a second on your hardware, and raise it over time; the cost stored in each hash lets you upgrade users transparently.
- Treat every JWT payload as world-readable: put identity and coarse role claims in it, never anything confidential.
- Verify the signature against a pinned algorithm and key before reading any claim, and reject tokens whose header proposes a different or
nonealgorithm.
- Always validate expiry, allowing only a small configured clock-skew leeway, and keep access-token lifetimes short.
- Pair short-lived access tokens with server-side refresh tokens so that logout and "sign out everywhere" have something real to revoke.
- Load the signing secret from the environment or a secret manager, keep it long and random, and use a different value per environment so a staging leak cannot sign production tokens.
- Return identical responses for unknown-user and wrong-password failures, and log the distinguishing detail only on the server.
Practice Exercises
- A token's payload decodes to
{"sub":"bob","role":"ADMIN","iat":1000,"exp":1600}. Given a fixed clock at second 1600, state whether it is accepted and why, and explain what an attacker who reads the payload learns and what they still cannot do.
- Your BCrypt logins feel slow under load at cost 12. A colleague proposes dropping to cost 8. Quantify the change in attacker work using the
2^costrule, and explain the security consequence of the drop.
- A reviewer finds a login that stores SHA-256 password hashes, returns "unknown email" when the account is missing, and signs 30-day tokens with a secret committed to
application.yml. List each problem and the concrete change you would make.
- A "Log out" endpoint only deletes the token from the browser. Using the idea that a stateless token stays valid until
exp, describe an attack this fails to stop and give two designs that actually revoke access.