Build one by hand, then read it back
Every misconception about JWTs dissolves once you have built one yourself. No dependencies needed — Node’s own crypto is enough:
import { createHmac } from 'node:crypto';
const b64u = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
const secret = 'dev-secret-not-a-real-key';
const h = b64u({ alg: 'HS256', typ: 'JWT' });
const p = b64u({ sub: 'u_1024', role: 'user', exp: 1790000000 });
const s = createHmac('sha256', secret).update(`${h}.${p}`).digest('base64url');
console.log(`${h}.${p}.${s}`);
Run on Node v22.17.1 / macOS 26.5.2. Every example below uses this one token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1XzEwMjQiLCJyb2xlIjoidXNlciIsImV4cCI6MTc5MDAwMDAwMH0.1Uq490UTCjQu_qA7RScjHcHUgT65G2nBnogsqjkr3P0
Three dot-separated segments, 36 / 63 / 43 characters. Decode the first two and you get back exactly the JSON objects you just wrote — not a byte changed:
Buffer.from(h, 'base64url').toString(); // {"alg":"HS256","typ":"JWT"}
Buffer.from(p, 'base64url').toString(); // {"sub":"u_1024","role":"user","exp":1790000000}
Buffer.from(s, 'base64url').length; // 32
The third segment decodes to 32 bytes, not text — that is HMAC-SHA256 output, 256 bits. It is not “the first two segments encrypted”; the first two were never hidden. It is a fixed-length digest computed over them.
While we are here, an observation everyone has seen and few have chased down: nearly every JWT starts with eyJ. A compactly serialised header JSON necessarily begins {" followed by a letter, and {"a encodes to eyJh while {"z encodes to eyJ6. The first three characters are invariant. No magic prefix — just how Base64 aligns.
Base64URL is not encryption, and it differs from Base64 in three characters
“Is a JWT encrypted?” keeps getting asked largely because the long opaque string looks like ciphertext. It is not. Base64URL is an encoding: reversible, keyless, public. It differs from Base64 in exactly three places — + becomes -, / becomes _, and trailing = padding is dropped. Five bytes show all three at once:
const b = Buffer.from([0xfb, 0xef, 0xbe, 0x3f, 0xff]);
b.toString('base64'); // '++++P/8='
b.toString('base64url'); // '----P_8'
Those substitutions exist so the output can appear safely in URL paths, query strings and HTTP headers without a second round of percent-encoding. They also set a trap: many command-line base64 tools accept neither -/_ nor missing padding, and fail silently. On macOS, feed the payload segment straight to base64 -d:
T='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1XzEwMjQiLCJyb2xlIjoidXNlciIsImV4cCI6MTc5MDAwMDAwMH0.1Uq490UTCjQu_qA7RScjHcHUgT65G2nBnogsqjkr3P0'
echo "$T" | cut -d. -f2 | base64 -d
# {"sub":"u_1024","role":"user","exp":179000000
Exit code 0, no warning. The payload is 63 characters; 63 mod 4 is 3, so the final group is one = short of complete, and the FreeBSD base64 that ships with macOS discards that incomplete group entirely — losing the two characters 0}.
Look at the shape of the damage. The closing brace is gone, so the output is not even valid JSON. More insidiously, exp went from 1790000000 to 179000000 — one digit shorter, and still looks like a perfectly plausible timestamp. This particular segment happens to contain no - or _, so padding alone did the damage; the signature segment fails differently, since it contains a _. base64 -d says nothing there either and emits 30 bytes where a real HMAC-SHA256 signature is 32.
Node’s base64url decoder has no such problem:
node -e "console.log(Buffer.from(process.argv[1].split('.')[1],'base64url').toString())" "$T"
# {"sub":"u_1024","role":"user","exp":1790000000}
The conclusion is direct: every claim in the payload is plaintext to anyone holding the token. User IDs, roles and tenant identifiers are fine, because they describe the holder’s own identity. Internal primary keys, phone numbers, email addresses, anything you would not write to a log — those do not belong there. The signature guarantees “unaltered”, not “unreadable”.
The signature covers the first two segments, and only those
The signing input is the string headerSegment + "." + payloadSegment — the encoded segments as text, not the decoded objects. So any byte change in either breaks it. Tampering with the payload is caught, and so is changing a header field that has nothing to do with the algorithm:
const sign = (h, p) => createHmac('sha256', secret).update(`${h}.${p}`).digest('base64url');
// role from user to admin, reusing the original signature segment
sign(h, b64u({ sub: 'u_1024', role: 'admin', exp: 1790000000 })) === s; // false
// only typ, from JWT to at+jwt, reusing the original signature segment
sign(b64u({ alg: 'HS256', typ: 'at+jwt' }), p) === s; // false
Both false. Stated precisely: a passing signature check proves one sentence — this combination of header and payload was issued by someone holding the key, and nothing has changed since. What it does not prove is a much longer list. It does not prove the token is unexpired. It does not prove it has not been revoked. It does not prove it was issued for your service. It does not prove the user still holds that role. Every one of those needs a separate check, and none of those checks is cryptography.
The root cause, in one sentence: the verifier believed the token’s own claim about the algorithm
The verification function below reads very naturally — naturally enough that many people do not spot the problem first time:
function naiveVerify(token, hmacKey, rsaPublicKey) {
const [h, p, s] = token.split('.');
const alg = JSON.parse(Buffer.from(h, 'base64url').toString()).alg; // ← the bug is this line
if (alg === 'none') return true;
if (alg === 'HS256') return s === createHmac('sha256', hmacKey).update(`${h}.${p}`).digest('base64url');
if (alg === 'RS256') return createVerify('RSA-SHA256').update(`${h}.${p}`)
.verify(rsaPublicKey, Buffer.from(s, 'base64url'));
return false;
}
alg is read from the header, and the header is one of the two segments an attacker can rewrite freely. So the decision of how to verify this token has been handed to the token awaiting verification.
The shortest exploit is alg: none. The spec reserves that value for cases where integrity is assured by other means, such as the transport layer — but in an implementation that does whatever the header says, it reads as “do not check”:
const forged = `${b64u({ alg: 'none', typ: 'JWT' })}.${b64u({ sub: 'u_1024', role: 'admin', exp: 1790000000 })}.`;
// eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1XzEwMjQiLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3OTAwMDAwMDB9.
naiveVerify(forged, secret); // true — and role is now admin
Note the lone trailing dot: the third segment is empty because the attacker deleted the signature outright. Forging this needs no key, no brute force, and no understanding of HMAC. Change HS256 to none, rewrite the payload, empty the signature. Three steps.
The same root cause wearing a second face: HS256 / RS256 confusion
alg: none is famous enough that most libraries now reject it explicitly. But while the root cause — the token declaring its own algorithm — survives, the same hole reappears in a different shape, this time without any suspicious value anywhere.
The setup is a server using RS256: private key signs, public key verifies. A public key is by definition public — it may be served at /.well-known/jwks.json, or printed in your API docs. The attacker takes that public key, changes alg to HS256, and then uses the public key’s text as the HMAC secret:
const pub = publicKey.export({ type: 'spki', format: 'pem' }); // a public artefact
const hh = b64u({ alg: 'HS256', typ: 'JWT' });
const pp = b64u({ sub: 'u_1024', role: 'admin', exp: 1790000000 });
const forged = `${hh}.${pp}.${createHmac('sha256', pub).update(`${hh}.${pp}`).digest('base64url')}`;
naiveVerify(forged, pub, pub); // true
Measured result: true. The reason is mundane. The verifier holds one piece of key material — the public key. It reads “this is HS256” in the header and uses that material as an HMAC shared secret. HMAC verifies and signs with the same key, so a key that was only ever supposed to verify has been demoted into a signing key that everybody already has.
Incidentally the two token types look obviously different: an RS256 (2048-bit) signature segment is 342 characters, an HS256 one is 43. You can tell them apart by eye. No code ever looks.
Doing it right: the verifier dictates the algorithm
One fix covers both attacks, and it is a single sentence: the verifier decides which algorithms it accepts and which key to use, then checks the token against that — never the other way round. From then on alg in the header has exactly one purpose: to be compared against what you decided, and to cause rejection when it differs.
function verify(token, { algorithms, secret, now = Math.floor(Date.now() / 1000), leeway = 60 }) {
const parts = token.split('.');
if (parts.length !== 3) return { ok: false, why: 'not three segments' };
const [h, p, s] = parts;
const head = JSON.parse(Buffer.from(h, 'base64url').toString());
if (!algorithms.includes(head.alg)) return { ok: false, why: `algorithm ${head.alg} not allowed` };
const expect = Buffer.from(createHmac('sha256', secret).update(`${h}.${p}`).digest('base64url'), 'base64url');
const got = Buffer.from(s, 'base64url');
if (got.length !== expect.length || !timingSafeEqual(got, expect)) return { ok: false, why: 'signature mismatch' };
const c = JSON.parse(Buffer.from(p, 'base64url').toString());
if (typeof c.exp === 'number' && now > c.exp + leeway) return { ok: false, why: 'expired' };
if (typeof c.nbf === 'number' && now + leeway < c.nbf) return { ok: false, why: 'not yet valid' };
return { ok: true, claims: c };
}
Feeding it the same tokens: the original returns {"ok":true,...}, the alg: none forgery returns {"ok":false,"why":"algorithm none not allowed"}, and an expired token returns {"ok":false,"why":"expired"}. The HS256/RS256 confusion token, with the allow-list set to ['RS256'], is stopped at the algorithm gate — {"ok":false,"why":"algorithm HS256 not allowed"} — and never reaches signature checking at all.
Several details deserve calling out individually. The algorithm list is an allow-list, not a deny-list — rejecting only none is not enough, since the previous section’s attack used no suspicious value. Bind keys to algorithms: HS256 to a shared secret, RS256 to a public key, and never let one piece of material serve both branches — that sharing is exactly where confusion attacks land. Compare signatures with timingSafeEqual, not ===; string comparison can return at the first differing character, making the time vary with how much of the prefix an attacker has guessed. Order matters: verify the signature, then read the claims. Until the signature passes, every field in the payload was written by the attacker.
exp is just a number, and not checking it means it does nothing
exp, nbf and iat are ordinary JSON fields. The signature guarantees nobody altered them; it does not compare them for you. This is very concrete in practice: a token with exp of 1789000000 (2026-09-10T00:26:40Z, four days before this article’s original measurement), signed correctly, handed to the naiveVerify above — returns true. The signature really is valid, the token really was issued by me, and it really has expired. “Signature valid” and “token usable” are two different questions, and the second one is not answered by cryptography. It is answered by your if statement.
Per RFC 7519 all three fields are NumericDate — Unix timestamps in seconds. JavaScript’s Date wants milliseconds, three orders of magnitude apart, which makes this a reliable bug source. Write Date.now() straight into exp and the token effectively never expires; pass exp straight to new Date() and you land somewhere in 1970, so every request 401s. For more shapes that thousandfold gap takes in practice, see three traps in Unix timestamps.
Also leave some clock tolerance — the leeway above. Issuer and verifier are different machines, NTP drifts, and a few dozen seconds of slack eliminates a whole class of “expired the moment it was issued” mystery reports.
Revocation is something a signature structurally cannot express
Expiry is at least written into the token. Revocation has nowhere to be written at all. Look again at that verify() function: it performs no I/O anywhere — no database query, no network call, everything computed locally. That is precisely why JWTs get chosen, since the verifier need not share session storage with the issuer. Said the other way round: once a token is issued, the server no longer holds any control over it.
Concretely: a user changes their password, and a token issued thirty minutes ago with twenty minutes left still works. An admin disables an account, and tokens already out there still work. You demote role from admin to user, and the old token’s admin stays valid until it expires by itself. None of these are implementation bugs; they follow necessarily from “the verifier only computes locally”. It has no channel through which to learn what you changed.
There are exactly two mitigations, both with a price. Shorten exp — five to fifteen minutes for an access token, paired with a refresh token you can revoke server-side; the cost is the complexity of refresh logic and a new attack surface in the refresh endpoint. Introduce state that must be queried — a revocation list keyed by jti, or a version number on the user record echoed in the token with a mismatch causing rejection; the cost is a read on every verification, which hands back the stateless-verification selling point.
There is no third option. Either you tolerate a window of known length, or you spend a lookup to close it. Which one is a business decision — but it has to be a decision somebody actually made, not an assumption that “we use JWTs, so logout is presumably instant”.
What this decoder can and cannot tell you
The JWT decoder on this site decodes only. It does not verify. Not because verification is hard to implement, but because verification needs a key, and asking you for a production signing key is itself the wrong thing to do — especially for HMAC, where the verifying key and the signing key are the same, so handing it over hands over the ability to mint tokens in your name. A web page can promise “nothing is uploaded”, but you have no way to confirm that promise before pasting. Decoding needs no key at all, so the tool does the part that can be done safely.
There is an earlier boundary too: the decoder handles three-segment tokens. If what you pasted has five segments, it is probably not a JWT but a JWE — RFC 7516’s compact serialisation is protected-header, encrypted-key, IV, ciphertext, auth-tag, and the actual payload there is encrypted, so without the key it is binary noise that no decoder will turn into prose. When the segment count is wrong, work out which kind of object you are holding before suspecting the tool.
So, the boundary stated plainly: this tool tells you what a token says — the contents of each segment, what exp converts to in your local time, whether it has expired according to your machine’s clock. It cannot tell you whether a token is genuine. A token that decodes cleanly, is well formed and has not expired can perfectly well be the three-step forgery from earlier in this article. The only thing that answers “can I trust this” is the server holding the key — and the way it answers is the sentence this article keeps returning to: it dictates the algorithm itself, and does not ask the token.