JWT security: the decisions your verifier must make before it trusts a token
A JSON Web Token is only as trustworthy as the code that checks it.
This guide explains in plain English what a JWT is and who can read it, the algorithm, key, claim and revocation decisions a verifier has to make, the attacks that work when one is skipped, and a verification suite you run with Node.js alone to show your own verifier makes each one.
In this guide
JWT verification suite and decision table
An illustration with invented issuers and users, for learning and for testing a verifier you own. Part 1 maps eleven verifier decisions (format, header parameters, token type, issuer, algorithm, key selection, signature, required claims, validity time, audience and revocation) to the specification section or requirement behind each and the fixtures that test it.
How to use itHide the instructions
Parts 2 to 5 are a Node.js suite with no installs: a token minter using keys generated at run time, a flawed and a fixed verifier, sixteen fixtures printed with each verifier's decision and reason, a regression test that fails on the flawed verifier, and steps to point the fixtures at your own verifier.
jwt-security.txt
Introduction17 lines
Part 1: The decision table134 lines
Part 2: The suite files550 lines
Part 3: Run the sixteen fixtures against both verifiers208 lines
Part 4: The regression test121 lines
Part 5: Point the fixtures at your own verifier6 lines
Whole template1,064 lines
JWT VERIFICATION SUITE AND DECISION TABLE
An illustration, for learning and for testing a JWT verifier you own. Every token in it is minted by the suite with keys it generates when it starts, and checked only by the suite's own two verifiers. Nothing in it contacts another machine, and it holds no real token, key or secret. The issuers, the API and the users are invented.
Written and run on: Node.js 26.0.0, the only version it was run on. It uses node:crypto, node:test and node:assert, which ship with Node.js, so there is nothing to install. Every output below was copied from that run. The keys and each jti are new on every run, so the end of each printed token differs every time; the runner shortens each token to its first 16 and last 6 characters for that reason. Test timings differ too.
Source names used below:
RFC 7519 RFC 7519, JSON Web Token (JWT)
RFC 7515 RFC 7515, JSON Web Signature (JWS)
RFC 7518 RFC 7518, JSON Web Algorithms (JWA)
RFC 8725 RFC 8725, JSON Web Token Best Current Practices (BCP 225)
RFC 9068 RFC 9068, JSON Web Token (JWT) Profile for OAuth 2.0 Access Tokens
RFC 9700 RFC 9700, Best Current Practice for OAuth 2.0 Security
ASVS OWASP Application Security Verification Standard 5.0.0, chapters V9 Self-contained Tokens and V7 Session Management. The level follows each requirement number.
WSTG-SESS-10 OWASP Web Security Testing Guide, latest edition, 4.6.10 JSON Web Tokens
OWASP JWT OWASP JSON Web Token Cheat Sheet
CWE MITRE CWE version 5.0
================================================================
PART 1: THE DECISION TABLE
The fixed verifier makes these eleven decisions in this order and reports
the first one a token fails. Each answer comes from the verifier's own
configuration. The token supplies only the values being checked.
D1 Format
Fixed verifier: exactly three parts, every character base64url, and a
JSON object in the header and the claims
Basis: RFC 7515 5.2 step 1, exactly two period characters in the
compact form; RFC 7519 7.2 steps 3 and 9, no line breaks,
whitespace or other characters; RFC 7519 7.2, if any step
fails the JWT MUST be rejected
Fixtures: none (every fixture is well formed)
D2 Header parameters, and where keys come from
Fixed verifier: only alg, typ and kid are accepted; jwk, jku, x5u, x5c
or any other parameter refuses the token, so no key is ever
read from it. Refusing every parameter other than alg, typ
and kid is this suite's own choice; the bases below support
not taking keys from jwk, jku or x5u
Basis: RFC 7519 7.2 step 5, only parameters the verifier understands
and supports, or that are specified as being ignored when not
understood; ASVS 9.1.3 (Level 1), key material from trusted
pre-configured sources, with jku, x5u and jwk validated
against an allowlist; RFC 8725 3.10, applications SHOULD
protect against jku and x5u SSRF; OWASP JWT, do not take the
verification key from the token unless it chains to a trust
anchor for the issuer
Fixtures: F05
D3 Token type
Fixed verifier: typ, read as a media type (case ignored, application/
assumed when there is no slash), must be application/at+jwt
Basis: RFC 9068 4, the resource server MUST verify typ is at+jwt or
application/at+jwt and reject any other value; RFC 7515 4.1.9;
RFC 8725 3.11, explicit typing RECOMMENDED for new uses, and
3.12, where one issuer issues more than one kind of JWT, the
validation rules MUST be mutually exclusive; ASVS 9.2.2
(Level 2)
Fixtures: F09
D4 Issuer
Fixed verifier: iss must exactly equal an issuer in the configuration;
this suite configures one
Basis: RFC 9068 4, the issuer identifier MUST exactly match iss;
RFC 7519 4.1.1 and section 2, case-sensitive with no
transformations; WSTG-SESS-10, exact equality rather than a
prefix or substring match
Fixtures: F07
D5 Algorithm
Fixed verifier: alg must equal the one algorithm set in code for that
issuer (RS256); never read from the token
Basis: RFC 8725 3.1, libraries MUST let the caller specify the
algorithms and MUST NOT use any other, and each key MUST be
used with exactly one algorithm; RFC 8725 3.2, applications
MUST only allow cryptographically current algorithms;
RFC 7515 5.2 and RFC 7519 7.2, unless the algorithm is
acceptable to the application it SHOULD treat the token as
invalid; RFC 7518 3.6, Unsecured JWSs MUST NOT be accepted by
default; RFC 9068 4, MUST reject alg none; ASVS 9.1.2 (Level 1)
Fixtures: F03 (alg none), F04 (HS256 with the public key as secret)
D6 Key selection
Fixed verifier: kid is looked up only among the keys configured for the
issuer named in iss; a kid not found there refuses the token
Basis: RFC 8725 3.8, when the JWT contains iss, the application MUST
validate that the keys belong to that issuer and MUST reject
the JWT if they do not;
ASVS 9.1.3 (Level 1); RFC 9068 4, MUST use the keys provided
by the authorisation server; RFC 7515 Appendix D, trust
decisions about keys; OWASP JWT, never verify against a union
of keys from several issuers
Fixtures: F06
D7 Signature
Fixed verifier: RS256 signature checked over the header and payload with
the selected key; no match refuses the token
Basis: RFC 7515 5.2 step 8; RFC 8725 3.3, every cryptographic
operation MUST be validated and the entire JWT MUST be
rejected if any fails; ASVS 9.1.1 (Level 1); CWE-347. For
HMAC algorithms, RFC 7518 3.2: the comparison MUST be
constant-time
Fixtures: F02 (both verifiers refuse it)
D8 Required claims
Fixed verifier: iss, sub, aud, exp, iat, jti and client_id must be present
Basis: RFC 9068 2.2, all seven REQUIRED in a JWT access token;
RFC 7519 4.1, applications should define which claims they
use and when they are required
Fixtures: F13
D9 Validity time and clock skew
Fixed verifier: refused when the time is at or after exp plus 60 seconds,
or before nbf minus 60 seconds
Basis: RFC 7519 4.1.4 and 4.1.5, MUST NOT be accepted for processing
outside that time, and implementers MAY provide some small
leeway, usually no more than a few minutes, for clock skew;
RFC 9068 4; ASVS 9.2.1 (Level 1)
Who sets the skew: RFC 7519 lets implementers provide some small leeway
and says it is usually no more than a few minutes. The 60
seconds used here is this suite's own choice.
Fixtures: F10, F11 (inside the leeway, accepted), F12
D10 Audience
Fixed verifier: aud, a string or an array, must contain this API's
identifier, compared exactly
Basis: RFC 7519 4.1.3, when aud is present, a recipient not named in
it MUST reject the JWT; RFC 8725 3.9, where one issuer issues JWTs for more than
one relying party, aud MUST be present and validated; RFC 9068
4 (MUST); ASVS 9.2.3 (Level 2); RFC 9700 2.3
Fixtures: F08
D11 Revocation
Fixed verifier: refused when the jti is on the revoked list, or when iat
is at or before the time the user last signed out everywhere
Basis: ASVS 7.4.1 (Level 1), self-contained tokens need a solution
such as a list of terminated tokens, disallowing tokens
produced before a per-user date and time, or rotating a
per-user signing key; RFC 7519 4.1.7, jti can be used to
prevent replay; OWASP JWT, a deny list based on jti and iss,
because keying it on the raw token or its hash is not safe
Fixtures: F14, F15, F16 (issued after the cut-off, accepted)
Not covered by the suite, and still your decision:
Subject RFC 8725 3.8: when the JWT contains sub, the application
MUST validate that it corresponds to a valid subject or
issuer-subject pair
Key strength RFC 7518 3.3: RSA keys of 2048 bits or larger MUST be used;
RFC 7518 3.2: HMAC keys at least the hash size MUST be used;
RFC 8725 3.5: human-memorisable passwords MUST NOT be used
directly as HMAC keys
kid handling RFC 8725 3.10: validate or sanitise kid before any lookup
Encryption RFC 8725 3.3: in a nested JWT, both the outer and inner
operations MUST be validated
================================================================
PART 2: THE SUITE FILES
================================================================
Make an empty folder, save the five files below into it with the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 5: jwt-tokens.mjs
================================================================
// jwt-tokens.mjs: the suite's keys and its token minter. Illustration only.
// Every key is generated when the suite starts and lives only in memory, and
// nothing in the suite contacts another machine. The issuers, the API and the
// users are invented; example.com addresses are used here as placeholders.
import { createHmac, generateKeyPairSync, randomUUID, sign } from 'node:crypto'
export const PRODUCTION_ISSUER = 'https://login.example.com'
export const STAGING_ISSUER = 'https://staging-login.example.com'
export const API_AUDIENCE = 'https://api.example.com'
export const WEB_APP_CLIENT_ID = 'lab-web-app'
// One fixed clock for the whole run, in seconds since 1970 (1 January 2026,
// 00:00 UTC), so every fixture is judged against the same time and the
// output is the same on every run. A real verifier reads the current time.
export const LAB_NOW = 1767225600
function createRsaKeyPair() {
return generateKeyPairSync('rsa', { modulusLength: 2048 })
}
// Three key pairs. The production and staging sign-in services each publish
// the public half of theirs. The outsider key belongs to nobody the API
// trusts; it stands in for a key pair anyone can make.
export function createLabKeys() {
return {
production: { kid: 'login-2026-01', pair: createRsaKeyPair() },
staging: { kid: 'staging-2026-01', pair: createRsaKeyPair() },
outsider: { kid: 'outsider-key', pair: createRsaKeyPair() },
}
}
// A public key as PEM text, a form verifiers can keep keys in.
export function publicKeyText(service) {
return service.pair.publicKey.export({ type: 'spki', format: 'pem' })
}
export function encodePart(value) {
return Buffer.from(JSON.stringify(value)).toString('base64url')
}
export function decodePart(part) {
return JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
}
function signingInputOf(header, claims) {
return encodePart(header) + '.' + encodePart(claims)
}
// RS256 is RSASSA-PKCS1-v1_5 using SHA-256 (RFC 7518 section 3.3). The lab
// calls node:crypto sign() with SHA-256 and its default RSA padding,
// RSA_PKCS1_PADDING (Node.js crypto documentation).
export function mintRs256(header, claims, privateKey) {
const signingInput = signingInputOf(header, claims)
const signature = sign('sha256', Buffer.from(signingInput), privateKey)
return signingInput + '.' + signature.toString('base64url')
}
// HS256: HMAC with SHA-256 (RFC 7518 section 3.2). The key-confusion fixture
// passes the text of an RSA public key here as the secret, which is the
// case RFC 8725 section 2.1 describes.
export function mintHs256(header, claims, secretText) {
const signingInput = signingInputOf(header, claims)
const mac = createHmac('sha256', secretText).update(signingInput).digest()
return signingInput + '.' + mac.toString('base64url')
}
// An Unsecured JWT: alg none and an empty signature (RFC 7519 section 6).
export function mintUnsigned(header, claims) {
return signingInputOf(header, claims) + '.'
}
// The header a JWT access token carries (RFC 9068 section 2.1).
export function accessTokenHeader(kid) {
return { alg: 'RS256', typ: 'at+jwt', kid: kid }
}
// The claims RFC 9068 section 2.2 requires in a JWT access token, plus a
// scope, for an invented user, valid from a minute ago for five minutes
// more. Each fixture changes one thing. jti is a random UUID, one way to
// give each token the unique identifier RFC 7519 section 4.1.7 describes.
export function accessTokenClaims(changes) {
const claims = {
iss: PRODUCTION_ISSUER,
sub: 'user-1001',
aud: API_AUDIENCE,
client_id: WEB_APP_CLIENT_ID,
scope: 'orders:read',
iat: LAB_NOW - 60,
exp: LAB_NOW + 300,
jti: randomUUID(),
}
return Object.assign(claims, changes)
}
================================================================
FILE 2 OF 5: jwt-verifiers.mjs
================================================================
// jwt-verifiers.mjs: two verifiers for the JWT access tokens an API receives.
// Illustration only. The flawed verifier checks a signature, so a tampered
// token fails, but it lets the token choose its own algorithm and key and
// checks no claim. Each of its mistakes is marked FLAWED. The fixed verifier
// makes every decision from its own configuration, in the order of the
// decision table (D1 to D11).
import { createHmac, createPublicKey, timingSafeEqual, verify } from 'node:crypto'
import { API_AUDIENCE, PRODUCTION_ISSUER, decodePart, publicKeyText } from './jwt-tokens.mjs'
function accept(reason) {
return { accepted: true, decision: 'none', reason: reason }
}
function refuse(decision, reason) {
return { accepted: false, decision: decision, reason: reason }
}
// ---------------------------------------------------------------------------
// The flawed verifier
// ---------------------------------------------------------------------------
// FLAWED: one table of every key the process has loaded, production and
// staging alike, stored as PEM text and found by kid alone.
export function createFlawedKeyTable(keys) {
const table = new Map()
table.set(keys.production.kid, publicKeyText(keys.production))
table.set(keys.staging.kid, publicKeyText(keys.staging))
return table
}
function chooseKeyFromHeader(header, keyTable) {
// FLAWED: a key carried in the token's own header is used as given.
if (header.jwk) {
const embedded = createPublicKey({ key: header.jwk, format: 'jwk' })
return { text: embedded.export({ type: 'spki', format: 'pem' }), description: 'the jwk in the token header' }
}
// FLAWED: kid is looked up across every issuer's keys.
if (keyTable.has(header.kid)) return { text: keyTable.get(header.kid), description: 'key ' + header.kid + ', found by kid' }
const firstKid = keyTable.keys().next().value
return { text: keyTable.get(firstKid), description: 'key ' + firstKid + ', the default' }
}
// FLAWED: the algorithm is whatever the header says.
function checkSignatureAsHeaderSays(alg, signingInput, encodedSignature, key) {
if (alg === 'none') return { valid: encodedSignature === '', how: 'alg none from the header, so no signature was checked' }
const signature = Buffer.from(encodedSignature, 'base64url')
if (alg === 'HS256') {
const expected = createHmac('sha256', key.text).update(signingInput).digest()
const valid = expected.length === signature.length && timingSafeEqual(expected, signature)
return { valid: valid, how: 'alg HS256 from the header, HMAC computed with the text of ' + key.description }
}
if (alg === 'RS256') {
const valid = verify('sha256', Buffer.from(signingInput), key.text, signature)
return { valid: valid, how: 'alg RS256 from the header, signature checked with ' + key.description }
}
return { valid: false, how: 'alg ' + alg + ' is not one it knows' }
}
export function verifyFlawed(token, keyTable) {
const parts = token.split('.')
if (parts.length !== 3) return refuse('D1', 'not three parts')
const header = decodePart(parts[0])
const key = chooseKeyFromHeader(header, keyTable)
const signingInput = parts[0] + '.' + parts[1]
const outcome = checkSignatureAsHeaderSays(header.alg, signingInput, parts[2], key)
if (!outcome.valid) return refuse('D7', outcome.how + ': no match')
// FLAWED: no claim is checked and no revocation is looked up.
return accept(outcome.how + '; no claim checked')
}
// ---------------------------------------------------------------------------
// The fixed verifier
// ---------------------------------------------------------------------------
// Everything the fixed verifier trusts is set here, in code, and none of it
// is read from a token: the one issuer this API accepts, the one algorithm
// and the keys for that issuer, this API's audience, the token types, the
// claims every token must carry and the clock leeway. The leeway is this
// suite's choice, inside the few minutes RFC 7519 section 4.1.4 mentions.
export function createApiConfig(keys) {
const productionKeys = new Map()
productionKeys.set(keys.production.kid, keys.production.pair.publicKey)
const issuers = new Map()
issuers.set(PRODUCTION_ISSUER, { algorithm: 'RS256', keys: productionKeys })
return {
issuers: issuers,
audience: API_AUDIENCE,
tokenType: 'application/at+jwt',
headerNames: ['alg', 'typ', 'kid'],
requiredClaims: ['iss', 'sub', 'aud', 'exp', 'iat', 'jti', 'client_id'],
leewaySeconds: 60,
}
}
// Revocation state checked on every request: token ids revoked one at a
// time, and the time each user last chose to sign out everywhere. With one
// issuer the jti alone names a token; with several, key the list on iss
// and jti together.
export function createRevocations() {
return { revokedTokenIds: new Set(), signedOutEverywhereAt: new Map() }
}
const BASE64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
function isBase64url(text) {
for (const character of text) {
if (!BASE64URL_ALPHABET.includes(character)) return false
}
return true
}
function readJsonObject(part) {
try {
const value = decodePart(part)
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null
} catch {
return null
}
}
// D1: exactly three base64url parts, and a JSON object in the first two.
function parseCompactToken(token) {
const parts = String(token).split('.')
if (parts.length !== 3) return { refusal: refuse('D1', 'a signed JWT has exactly three parts') }
if (!parts.every(isBase64url)) return { refusal: refuse('D1', 'a part holds characters outside base64url') }
const header = readJsonObject(parts[0])
const claims = readJsonObject(parts[1])
if (!header || !claims) return { refusal: refuse('D1', 'the header or claims are not a JSON object') }
return { header: header, claims: claims, signingInput: parts[0] + '.' + parts[1], signature: parts[2] }
}
// RFC 7515 section 4.1.9: media types ignore case, and a typ with no slash
// is read as if "application/" came first, so at+jwt is application/at+jwt.
function readMediaType(typ) {
const lowerCase = String(typ).toLowerCase()
return lowerCase.includes('/') ? lowerCase : 'application/' + lowerCase
}
// D2 and D3: only header parameters this verifier understands, and the
// token type of an access token.
function checkHeader(header, config) {
for (const name of Object.keys(header)) {
if (!config.headerNames.includes(name)) return refuse('D2', 'header parameter ' + name + ' is not accepted; keys come only from configuration')
}
if (readMediaType(header.typ) !== config.tokenType) return refuse('D3', 'typ ' + String(header.typ) + ' is not an access token type')
return null
}
// D7: RS256 with the configured key only.
function isSignatureValid(parsed, publicKey) {
const signature = Buffer.from(parsed.signature, 'base64url')
return verify('sha256', Buffer.from(parsed.signingInput), publicKey, signature)
}
// D8 to D10: required claims, validity time with the leeway, and audience.
function checkClaims(claims, config, now) {
const missing = config.requiredClaims.filter((name) => claims[name] === undefined)
if (missing.length) return refuse('D8', 'required claim missing: ' + missing.join(', '))
if (typeof claims.exp !== 'number' || now >= claims.exp + config.leewaySeconds) {
return refuse('D9', 'expired ' + (now - claims.exp) + ' seconds ago, beyond the ' + config.leewaySeconds + ' second leeway')
}
if (claims.nbf !== undefined && (typeof claims.nbf !== 'number' || now + config.leewaySeconds < claims.nbf)) {
return refuse('D9', 'not valid for another ' + (claims.nbf - now) + ' seconds')
}
const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud]
if (!audiences.includes(config.audience)) return refuse('D10', 'aud ' + audiences.join(', ') + ' does not include ' + config.audience)
return null
}
// D11: a revoked token id, or a token issued at or before the user's cut-off.
function checkRevocation(claims, revocations) {
if (revocations.revokedTokenIds.has(claims.jti)) return refuse('D11', 'this token id was revoked')
const cutOff = revocations.signedOutEverywhereAt.get(claims.sub)
if (cutOff !== undefined && claims.iat <= cutOff) {
return refuse('D11', 'issued ' + (cutOff - claims.iat) + ' seconds before ' + claims.sub + ' signed out everywhere')
}
return null
}
// iss is read before the signature check only to choose which configuration
// to check against. Nothing in the claims is trusted until D7 passes.
export function verifyFixed(token, config, revocations, now) {
const parsed = parseCompactToken(token)
if (parsed.refusal) return parsed.refusal
const headerProblem = checkHeader(parsed.header, config)
if (headerProblem) return headerProblem
const issuer = config.issuers.get(parsed.claims.iss)
if (!issuer) return refuse('D4', 'iss ' + String(parsed.claims.iss) + ' is not an issuer this API accepts')
if (parsed.header.alg !== issuer.algorithm) {
return refuse('D5', 'alg ' + String(parsed.header.alg) + ' is not the ' + issuer.algorithm + ' set for ' + parsed.claims.iss)
}
const publicKey = issuer.keys.get(parsed.header.kid)
if (!publicKey) return refuse('D6', 'kid ' + String(parsed.header.kid) + ' is not a key configured for ' + parsed.claims.iss)
if (!isSignatureValid(parsed, publicKey)) return refuse('D7', 'the signature does not match key ' + parsed.header.kid)
const claimProblem = checkClaims(parsed.claims, config, now) || checkRevocation(parsed.claims, revocations)
if (claimProblem) return claimProblem
return accept('every decision passed')
}
================================================================
FILE 3 OF 5: jwt-fixtures.mjs
================================================================
// jwt-fixtures.mjs: sixteen tokens, each minted for this run with the suite's
// own keys, and the decision the fixed verifier is expected to make on each.
// Illustration only: the tokens are for the suite's own verifiers.
import {
LAB_NOW, STAGING_ISSUER, WEB_APP_CLIENT_ID,
accessTokenClaims, accessTokenHeader, createLabKeys, encodePart,
mintHs256, mintRs256, mintUnsigned, publicKeyText,
} from './jwt-tokens.mjs'
import { createApiConfig, createFlawedKeyTable, createRevocations, verifyFixed, verifyFlawed } from './jwt-verifiers.mjs'
export function createLab() {
const keys = createLabKeys()
return { keys: keys, config: createApiConfig(keys), flawedKeyTable: createFlawedKeyTable(keys), revocations: createRevocations() }
}
function signAsProduction(lab, claimChanges) {
const production = lab.keys.production
return mintRs256(accessTokenHeader(production.kid), accessTokenClaims(claimChanges), production.pair.privateKey)
}
function signAsStaging(lab, claimChanges) {
const staging = lab.keys.staging
return mintRs256(accessTokenHeader(staging.kid), accessTokenClaims(claimChanges), staging.pair.privateKey)
}
// A genuine token whose claims are swapped after signing; the signature is left as it was.
function tamperWithScope(lab) {
const parts = signAsProduction(lab, {}).split('.')
const changed = accessTokenClaims({ scope: 'orders:read orders:write refunds:approve' })
return parts[0] + '.' + encodePart(changed) + '.' + parts[2]
}
function embedOutsiderKey(lab) {
const outsider = lab.keys.outsider
const header = accessTokenHeader(outsider.kid)
header.jwk = outsider.pair.publicKey.export({ format: 'jwk' })
return mintRs256(header, accessTokenClaims({}), outsider.pair.privateKey)
}
function revokeByTokenId(lab) {
const claims = accessTokenClaims({})
lab.revocations.revokedTokenIds.add(claims.jti)
const production = lab.keys.production
return mintRs256(accessTokenHeader(production.kid), claims, production.pair.privateKey)
}
// user-2002 chose "sign out everywhere" two minutes before the suite's clock.
function signOutUserEverywhere(lab) {
lab.revocations.signedOutEverywhereAt.set('user-2002', LAB_NOW - 120)
}
export const FIXTURES = [
{ id: 'F01', title: 'A valid access token from the production issuer', expected: 'accept',
madeBy: 'signed RS256 with the production key',
build: (lab) => signAsProduction(lab, {}) },
{ id: 'F02', title: 'Tampered claims, original signature', expected: 'refuse', decision: 'D7',
madeBy: 'a valid token whose scope was widened after signing',
build: tamperWithScope },
{ id: 'F03', title: 'Unsigned token (alg none)', expected: 'refuse', decision: 'D5',
madeBy: 'alg none and an empty signature',
build: (lab) => mintUnsigned({ alg: 'none', typ: 'at+jwt' }, accessTokenClaims({})) },
{ id: 'F04', title: 'Key confusion: HS256 with the RSA public key as the secret', expected: 'refuse', decision: 'D5',
madeBy: 'alg HS256, with the text of the production public key used as the HMAC secret',
build: (lab) => mintHs256({ alg: 'HS256', typ: 'at+jwt', kid: lab.keys.production.kid }, accessTokenClaims({}), publicKeyText(lab.keys.production)) },
{ id: 'F05', title: 'Key supplied in the header (embedded jwk)', expected: 'refuse', decision: 'D2',
madeBy: 'signed with the outsider key, whose public half rides in the jwk header',
build: embedOutsiderKey },
{ id: 'F06', title: "Another issuer's key: production iss, staging signature", expected: 'refuse', decision: 'D6',
madeBy: 'claims name the production issuer; signed with the staging key, kid staging-2026-01',
build: (lab) => signAsStaging(lab, {}) },
{ id: 'F07', title: 'Wrong issuer: a token from the staging sign-in service', expected: 'refuse', decision: 'D4',
madeBy: 'a genuine staging token, signed with the staging key',
build: (lab) => signAsStaging(lab, { iss: STAGING_ISSUER }) },
{ id: 'F08', title: 'Wrong audience: a token issued for the billing API', expected: 'refuse', decision: 'D10',
madeBy: 'a genuine production token for https://billing.example.com',
build: (lab) => signAsProduction(lab, { aud: 'https://billing.example.com' }) },
{ id: 'F09', title: 'Wrong token type: an ID token presented as an access token', expected: 'refuse', decision: 'D3',
madeBy: 'typ JWT and the web app as audience, signed with the production key',
build: (lab) => mintRs256({ alg: 'RS256', typ: 'JWT', kid: lab.keys.production.kid },
accessTokenClaims({ aud: WEB_APP_CLIENT_ID, scope: undefined, client_id: undefined, nonce: 'lab-nonce' }), lab.keys.production.pair.privateKey) },
{ id: 'F10', title: 'Expired ten minutes ago', expected: 'refuse', decision: 'D9',
madeBy: 'exp 600 seconds before the clock',
build: (lab) => signAsProduction(lab, { iat: LAB_NOW - 900, exp: LAB_NOW - 600 }) },
{ id: 'F11', title: 'Expired 30 seconds ago, inside the leeway', expected: 'accept',
madeBy: 'exp 30 seconds before the clock',
build: (lab) => signAsProduction(lab, { iat: LAB_NOW - 330, exp: LAB_NOW - 30 }) },
{ id: 'F12', title: 'Not valid yet (nbf ten minutes ahead)', expected: 'refuse', decision: 'D9',
madeBy: 'nbf 600 seconds after the clock',
build: (lab) => signAsProduction(lab, { nbf: LAB_NOW + 600, exp: LAB_NOW + 900 }) },
{ id: 'F13', title: 'No expiry (exp left out)', expected: 'refuse', decision: 'D8',
madeBy: 'a production token with no exp claim',
build: (lab) => signAsProduction(lab, { exp: undefined }) },
{ id: 'F14', title: 'Revoked by its token id (jti)', expected: 'refuse', decision: 'D11',
madeBy: 'a valid token whose jti is on the revoked list',
build: revokeByTokenId },
{ id: 'F15', title: 'Issued before the user signed out everywhere', expected: 'refuse', decision: 'D11',
madeBy: 'user-2002, iat 240 seconds before the clock; cut-off 120 seconds before it',
build: (lab) => { signOutUserEverywhere(lab); return signAsProduction(lab, { sub: 'user-2002', iat: LAB_NOW - 240, exp: LAB_NOW + 60 }) } },
{ id: 'F16', title: 'Issued after the user signed out everywhere', expected: 'accept',
madeBy: 'user-2002, iat 60 seconds before the clock, after the cut-off',
build: (lab) => { signOutUserEverywhere(lab); return signAsProduction(lab, { sub: 'user-2002' }) } },
]
export function runVerifier(version, token, lab) {
if (version === 'flawed') return verifyFlawed(token, lab.flawedKeyTable)
return verifyFixed(token, lab.config, lab.revocations, LAB_NOW)
}
// As expected: accepted when the fixture expects acceptance, otherwise
// refused at the decision the fixture names.
export function isAsExpected(fixture, outcome) {
if (fixture.expected === 'accept') return outcome.accepted
return !outcome.accepted && outcome.decision === fixture.decision
}
================================================================
FILE 4 OF 5: run-suite.mjs
================================================================
// run-suite.mjs: mints the sixteen fixtures, gives each to both verifiers and
// prints what each decided and why. Run: node run-suite.mjs
// Tokens are printed shortened: the keys and each jti are new on every run,
// so the end of each token differs every time.
import { LAB_NOW, decodePart } from './jwt-tokens.mjs'
import { FIXTURES, createLab, isAsExpected, runVerifier } from './jwt-fixtures.mjs'
const TIME_CLAIMS = ['iat', 'nbf', 'exp']
const IDENTITY_CLAIMS = ['iss', 'sub', 'aud']
function relativeTime(seconds) {
const offset = seconds - LAB_NOW
return offset < 0 ? 'now' + offset : 'now+' + offset
}
function describeHeader(header) {
return Object.keys(header).map((name) => {
if (name === 'jwk') return 'jwk (an RSA public key)'
return name + ' ' + header[name]
}).join(', ')
}
function describeClaim(name, claims) {
if (name === 'jti') return 'jti (random)'
if (TIME_CLAIMS.includes(name)) return name + ' ' + relativeTime(claims[name])
return name + ' ' + claims[name]
}
// Two lines: who issued the token, about whom and for whom, then the rest.
function describeClaims(claims) {
const names = Object.keys(claims)
const identity = names.filter((name) => IDENTITY_CLAIMS.includes(name))
const others = names.filter((name) => !IDENTITY_CLAIMS.includes(name))
return {
identity: identity.map((name) => describeClaim(name, claims)).join(', '),
others: others.map((name) => describeClaim(name, claims)).join(', '),
}
}
function shorten(token) {
return token.slice(0, 16) + '...' + token.slice(-6) + ' (' + token.length + ' characters)'
}
function describeOutcome(outcome) {
if (outcome.accepted) return 'accepted: ' + outcome.reason
return 'refused at ' + outcome.decision + ': ' + outcome.reason
}
function printFixture(fixture, lab, tally) {
const token = fixture.build(lab)
const parts = token.split('.')
const claims = describeClaims(decodePart(parts[1]))
console.log(fixture.id + ' ' + fixture.title)
console.log(' Made: ' + fixture.madeBy)
console.log(' Header: ' + describeHeader(decodePart(parts[0])))
console.log(' Claims: ' + claims.identity)
console.log(' ' + claims.others)
console.log(' Token: ' + shorten(token))
console.log(' Expected: ' + (fixture.expected === 'accept' ? 'accepted' : 'refused at ' + fixture.decision))
const verdicts = []
for (const version of ['flawed', 'fixed']) {
const outcome = runVerifier(version, token, lab)
const asExpected = isAsExpected(fixture, outcome)
if (asExpected) tally[version] = tally[version] + 1
console.log(' ' + version.toUpperCase().padEnd(9) + ' ' + describeOutcome(outcome))
verdicts.push(version + (asExpected ? ' as expected' : ' WRONG'))
}
console.log(' Result: ' + verdicts.join(', '))
console.log('')
}
function printSetup(lab) {
const config = lab.config
const issuer = config.issuers.keys().next().value
const settings = config.issuers.get(issuer)
console.log('Keys made for this run: login-2026-01 (production), staging-2026-01 (staging), outsider-key (trusted by neither)')
console.log('Fixed verifier accepts: iss ' + issuer + ', aud ' + config.audience)
console.log(' alg ' + settings.algorithm + ', kid ' + Array.from(settings.keys.keys()).join(', ') + ', typ ' + config.tokenType + ', leeway ' + config.leewaySeconds + ' seconds')
console.log("Times are shown against the suite's fixed clock, now.")
console.log('')
}
function main() {
const lab = createLab()
printSetup(lab)
const tally = { flawed: 0, fixed: 0 }
for (const fixture of FIXTURES) printFixture(fixture, lab, tally)
for (const version of ['flawed', 'fixed']) {
console.log(version + ' verifier: ' + tally[version] + ' of ' + FIXTURES.length + ' decisions as expected')
}
}
main()
================================================================
FILE 5 OF 5: jwt-verifier.test.mjs
================================================================
// jwt-verifier.test.mjs: the sixteen fixtures as a regression test.
// Run: node jwt-verifier.test.mjs (fixed verifier: all sixteen pass)
// node jwt-verifier.test.mjs flawed (flawed verifier: twelve fail)
// A failing test sets the exit code to 1, so a pipeline step running it fails.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { FIXTURES, createLab, isAsExpected, runVerifier } from './jwt-fixtures.mjs'
const version = process.argv[2] || 'fixed'
if (version !== 'fixed' && version !== 'flawed') throw new Error('Use fixed or flawed')
const lab = createLab()
for (const fixture of FIXTURES) {
const expected = fixture.expected === 'accept' ? 'accepted' : 'refused at ' + fixture.decision
test(fixture.id + ' ' + fixture.title + ': ' + expected, () => {
const outcome = runVerifier(version, fixture.build(lab), lab)
const actual = outcome.accepted ? 'accepted' : 'refused at ' + outcome.decision
assert.ok(isAsExpected(fixture, outcome), 'expected ' + expected + ', got ' + actual + ' (' + outcome.reason + ')')
})
}
================================================================
PART 3: RUN THE SIXTEEN FIXTURES AGAINST BOTH VERIFIERS
================================================================
For each fixture the runner prints how the token was made, its header and claims (times against the suite's fixed clock, now), the shortened token, the expected decision, and what each verifier decided and why.
Command: node run-suite.mjs
Keys made for this run: login-2026-01 (production), staging-2026-01 (staging), outsider-key (trusted by neither)
Fixed verifier accepts: iss https://login.example.com, aud https://api.example.com
alg RS256, kid login-2026-01, typ application/at+jwt, leeway 60 seconds
Times are shown against the suite's fixed clock, now.
F01 A valid access token from the production issuer
Made: signed RS256 with the production key
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJSUzI1...hsTmvQ (697 characters)
Expected: accepted
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED accepted: every decision passed
Result: flawed as expected, fixed as expected
F02 Tampered claims, original signature
Made: a valid token whose scope was widened after signing
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read orders:write refunds:approve, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJSUzI1...LB1_fA (736 characters)
Expected: refused at D7
FLAWED refused at D7: alg RS256 from the header, signature checked with key login-2026-01, found by kid: no match
FIXED refused at D7: the signature does not match key login-2026-01
Result: flawed as expected, fixed as expected
F03 Unsigned token (alg none)
Made: alg none and an empty signature
Header: alg none, typ at+jwt
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJub25l...RjIn0. (324 characters)
Expected: refused at D5
FLAWED accepted: alg none from the header, so no signature was checked; no claim checked
FIXED refused at D5: alg none is not the RS256 set for https://login.example.com
Result: flawed WRONG, fixed as expected
F04 Key confusion: HS256 with the RSA public key as the secret
Made: alg HS256, with the text of the production public key used as the HMAC secret
Header: alg HS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJIUzI1...Kr5mE0 (398 characters)
Expected: refused at D5
FLAWED accepted: alg HS256 from the header, HMAC computed with the text of key login-2026-01, found by kid; no claim checked
FIXED refused at D5: alg HS256 is not the RS256 set for https://login.example.com
Result: flawed WRONG, fixed as expected
F05 Key supplied in the header (embedded jwk)
Made: signed with the outsider key, whose public half rides in the jwk header
Header: alg RS256, typ at+jwt, kid outsider-key, jwk (an RSA public key)
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJSUzI1...qzHXhw (1202 characters)
Expected: refused at D2
FLAWED accepted: alg RS256 from the header, signature checked with the jwk in the token header; no claim checked
FIXED refused at D2: header parameter jwk is not accepted; keys come only from configuration
Result: flawed WRONG, fixed as expected
F06 Another issuer's key: production iss, staging signature
Made: claims name the production issuer; signed with the staging key, kid staging-2026-01
Header: alg RS256, typ at+jwt, kid staging-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJSUzI1...HMzXMg (699 characters)
Expected: refused at D6
FLAWED accepted: alg RS256 from the header, signature checked with key staging-2026-01, found by kid; no claim checked
FIXED refused at D6: kid staging-2026-01 is not a key configured for https://login.example.com
Result: flawed WRONG, fixed as expected
F07 Wrong issuer: a token from the staging sign-in service
Made: a genuine staging token, signed with the staging key
Header: alg RS256, typ at+jwt, kid staging-2026-01
Claims: iss https://staging-login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJSUzI1...n_N6wA (710 characters)
Expected: refused at D4
FLAWED accepted: alg RS256 from the header, signature checked with key staging-2026-01, found by kid; no claim checked
FIXED refused at D4: iss https://staging-login.example.com is not an issuer this API accepts
Result: flawed WRONG, fixed as expected
F08 Wrong audience: a token issued for the billing API
Made: a genuine production token for https://billing.example.com
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://billing.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJSUzI1...uc8LSA (702 characters)
Expected: refused at D10
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED refused at D10: aud https://billing.example.com does not include https://api.example.com
Result: flawed WRONG, fixed as expected
F09 Wrong token type: an ID token presented as an access token
Made: typ JWT and the web app as audience, signed with the production key
Header: alg RS256, typ JWT, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud lab-web-app
iat now-60, exp now+300, jti (random), nonce lab-nonce
Token: eyJhbGciOiJSUzI1...3LTlPg (640 characters)
Expected: refused at D3
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED refused at D3: typ JWT is not an access token type
Result: flawed WRONG, fixed as expected
F10 Expired ten minutes ago
Made: exp 600 seconds before the clock
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-900, exp now-600, jti (random)
Token: eyJhbGciOiJSUzI1...Ez50Ew (697 characters)
Expected: refused at D9
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED refused at D9: expired 600 seconds ago, beyond the 60 second leeway
Result: flawed WRONG, fixed as expected
F11 Expired 30 seconds ago, inside the leeway
Made: exp 30 seconds before the clock
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-330, exp now-30, jti (random)
Token: eyJhbGciOiJSUzI1...zh_QIg (697 characters)
Expected: accepted
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED accepted: every decision passed
Result: flawed as expected, fixed as expected
F12 Not valid yet (nbf ten minutes ahead)
Made: nbf 600 seconds after the clock
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+900, jti (random), nbf now+600
Token: eyJhbGciOiJSUzI1...pzUuxw (720 characters)
Expected: refused at D9
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED refused at D9: not valid for another 600 seconds
Result: flawed WRONG, fixed as expected
F13 No expiry (exp left out)
Made: a production token with no exp claim
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, jti (random)
Token: eyJhbGciOiJSUzI1...UhITNw (674 characters)
Expected: refused at D8
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED refused at D8: required claim missing: exp
Result: flawed WRONG, fixed as expected
F14 Revoked by its token id (jti)
Made: a valid token whose jti is on the revoked list
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-1001, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJSUzI1...CdMY-A (697 characters)
Expected: refused at D11
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED refused at D11: this token id was revoked
Result: flawed WRONG, fixed as expected
F15 Issued before the user signed out everywhere
Made: user-2002, iat 240 seconds before the clock; cut-off 120 seconds before it
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-2002, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-240, exp now+60, jti (random)
Token: eyJhbGciOiJSUzI1...mKO9Gg (697 characters)
Expected: refused at D11
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED refused at D11: issued 120 seconds before user-2002 signed out everywhere
Result: flawed WRONG, fixed as expected
F16 Issued after the user signed out everywhere
Made: user-2002, iat 60 seconds before the clock, after the cut-off
Header: alg RS256, typ at+jwt, kid login-2026-01
Claims: iss https://login.example.com, sub user-2002, aud https://api.example.com
client_id lab-web-app, scope orders:read, iat now-60, exp now+300, jti (random)
Token: eyJhbGciOiJSUzI1...sAfnhw (697 characters)
Expected: accepted
FLAWED accepted: alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked
FIXED accepted: every decision passed
Result: flawed as expected, fixed as expected
flawed verifier: 4 of 16 decisions as expected
fixed verifier: 16 of 16 decisions as expected
Reading the evidence:
F01 Both verifiers accept a genuine token.
F02 Both refuse: the flawed verifier does check signatures, so claims
changed after signing fail.
F03, F04 The flawed verifier lets alg decide. With alg none it checks no
signature; with HS256 it uses the public key's text as the HMAC
secret. The fixed verifier allows only RS256 for this issuer (D5).
F05 The flawed verifier checks the signature with the key the token
brought. The fixed verifier refuses the jwk header (D2).
F06 The flawed verifier finds the staging key by kid in its shared
table. The fixed verifier looks only among production's keys (D6).
F07 A genuine staging token. The flawed verifier never reads iss; the
fixed verifier accepts only the production issuer (D4).
F08, F09 Genuine production tokens meant for another API, or of another
kind: refused at D10 and D3.
F10 to F13 Time and required claims: refused at D9 and D8. F11 shows the
leeway: 30 seconds late is accepted, 600 seconds late is not.
F14 to F16 Revocation: a revoked jti and a token older than the user's
cut-off are refused (D11); a token issued after the cut-off is
accepted.
================================================================
PART 4: THE REGRESSION TEST
================================================================
The same sixteen fixtures, run by Node's built-in test runner. Run it in the pipeline that deploys your API.
Command: node jwt-verifier.test.mjs
✔ F01 A valid access token from the production issuer: accepted (2.301667ms)
✔ F02 Tampered claims, original signature: refused at D7 (0.63625ms)
✔ F03 Unsigned token (alg none): refused at D5 (0.094666ms)
✔ F04 Key confusion: HS256 with the RSA public key as the secret: refused at D5 (0.259292ms)
✔ F05 Key supplied in the header (embedded jwk): refused at D2 (0.786875ms)
✔ F06 Another issuer's key: production iss, staging signature: refused at D6 (0.755334ms)
✔ F07 Wrong issuer: a token from the staging sign-in service: refused at D4 (0.505125ms)
✔ F08 Wrong audience: a token issued for the billing API: refused at D10 (0.551959ms)
✔ F09 Wrong token type: an ID token presented as an access token: refused at D3 (0.531417ms)
✔ F10 Expired ten minutes ago: refused at D9 (0.618292ms)
✔ F11 Expired 30 seconds ago, inside the leeway: accepted (0.545458ms)
✔ F12 Not valid yet (nbf ten minutes ahead): refused at D9 (0.554125ms)
✔ F13 No expiry (exp left out): refused at D8 (0.537583ms)
✔ F14 Revoked by its token id (jti): refused at D11 (0.500834ms)
✔ F15 Issued before the user signed out everywhere: refused at D11 (0.507875ms)
✔ F16 Issued after the user signed out everywhere: accepted (0.495667ms)
ℹ tests 16
ℹ suites 0
ℹ pass 16
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 15.397125
The process exits with code 0.
Command: node jwt-verifier.test.mjs flawed
✔ F01 A valid access token from the production issuer: accepted (2.385084ms)
✔ F02 Tampered claims, original signature: refused at D7 (0.587875ms)
✖ F03 Unsigned token (alg none): refused at D5 (0.393792ms)
✖ F04 Key confusion: HS256 with the RSA public key as the secret: refused at D5 (0.216334ms)
✖ F05 Key supplied in the header (embedded jwk): refused at D2 (0.834666ms)
✖ F06 Another issuer's key: production iss, staging signature: refused at D6 (0.770541ms)
✖ F07 Wrong issuer: a token from the staging sign-in service: refused at D4 (0.56375ms)
✖ F08 Wrong audience: a token issued for the billing API: refused at D10 (0.5545ms)
✖ F09 Wrong token type: an ID token presented as an access token: refused at D3 (0.579916ms)
✖ F10 Expired ten minutes ago: refused at D9 (0.613625ms)
✔ F11 Expired 30 seconds ago, inside the leeway: accepted (0.599875ms)
✖ F12 Not valid yet (nbf ten minutes ahead): refused at D9 (0.588ms)
✖ F13 No expiry (exp left out): refused at D8 (0.573459ms)
✖ F14 Revoked by its token id (jti): refused at D11 (0.549542ms)
✖ F15 Issued before the user signed out everywhere: refused at D11 (0.546ms)
✔ F16 Issued after the user signed out everywhere: accepted (0.513583ms)
ℹ tests 16
ℹ suites 0
ℹ pass 4
ℹ fail 12
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 15.609083
✖ failing tests:
test at jwt-verifier.test.mjs:16:3
✖ F03 Unsigned token (alg none): refused at D5 (0.393792ms)
AssertionError [ERR_ASSERTION]: expected refused at D5, got accepted (alg none from the header, so no signature was checked; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F04 Key confusion: HS256 with the RSA public key as the secret: refused at D5 (0.216334ms)
AssertionError [ERR_ASSERTION]: expected refused at D5, got accepted (alg HS256 from the header, HMAC computed with the text of key login-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F05 Key supplied in the header (embedded jwk): refused at D2 (0.834666ms)
AssertionError [ERR_ASSERTION]: expected refused at D2, got accepted (alg RS256 from the header, signature checked with the jwk in the token header; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F06 Another issuer's key: production iss, staging signature: refused at D6 (0.770541ms)
AssertionError [ERR_ASSERTION]: expected refused at D6, got accepted (alg RS256 from the header, signature checked with key staging-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F07 Wrong issuer: a token from the staging sign-in service: refused at D4 (0.56375ms)
AssertionError [ERR_ASSERTION]: expected refused at D4, got accepted (alg RS256 from the header, signature checked with key staging-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F08 Wrong audience: a token issued for the billing API: refused at D10 (0.5545ms)
AssertionError [ERR_ASSERTION]: expected refused at D10, got accepted (alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F09 Wrong token type: an ID token presented as an access token: refused at D3 (0.579916ms)
AssertionError [ERR_ASSERTION]: expected refused at D3, got accepted (alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F10 Expired ten minutes ago: refused at D9 (0.613625ms)
AssertionError [ERR_ASSERTION]: expected refused at D9, got accepted (alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F12 Not valid yet (nbf ten minutes ahead): refused at D9 (0.588ms)
AssertionError [ERR_ASSERTION]: expected refused at D9, got accepted (alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F13 No expiry (exp left out): refused at D8 (0.573459ms)
AssertionError [ERR_ASSERTION]: expected refused at D8, got accepted (alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F14 Revoked by its token id (jti): refused at D11 (0.549542ms)
AssertionError [ERR_ASSERTION]: expected refused at D11, got accepted (alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
test at jwt-verifier.test.mjs:16:3
✖ F15 Issued before the user signed out everywhere: refused at D11 (0.546ms)
AssertionError [ERR_ASSERTION]: expected refused at D11, got accepted (alg RS256 from the header, signature checked with key login-2026-01, found by kid; no claim checked)
(stack trace and error details removed here)
The process exits with code 1, so a pipeline step running the test fails.
================================================================
PART 5: POINT THE FIXTURES AT YOUR OWN VERIFIER
1. Copy jwt-tokens.mjs, jwt-fixtures.mjs and jwt-verifier.test.mjs into your project's tests.
2. Change PRODUCTION_ISSUER and API_AUDIENCE in jwt-tokens.mjs to your issuer and API identifiers.
3. In jwt-fixtures.mjs, change runVerifier so the fixed version calls your verifier, configured as in production except that its trusted key for your issuer is the suite's production public key. Keep the staging and outsider keys out of that configuration: they exist to be refused.
4. Give your verifier the suite's clock, LAB_NOW, as its current time. The jsonwebtoken README names this option clockTimestamp, in seconds; the jose documentation names it currentDate, as a Date.
5. If your verifier does not say which check failed, change isAsExpected to compare accepted or refused only, and record the reason your verifier gives.
6. Run it in your test environment and in the pipeline that deploys your API. Use it on verifiers you own or are authorised in writing to test, never against a live service.What a JSON Web Token is, and who can read it
A JSON Web Token, or JWT, is a short piece of text that carries statements about someone, protected so the receiver can tell whether they were changed.
RFC 7519, the IETF standard that defines it, calls it a compact claims representation format intended for space constrained environments such as HTTP Authorization headers and URI query parameters. The statements are claims: name and value pairs in a JSON object. That object is either the payload of a JSON Web Signature (JWS), which signs it or protects it with a message authentication code (MAC), or the plaintext of a JSON Web Encryption (JWE) structure, which encrypts it. This guide is about the signed kind.
A signed JWT is three pieces of base64url text joined by full stops. RFC 7515 section 3.1 gives the compact form as the encoded protected header, then the encoded payload, then the encoded signature. The header says how the token was protected: alg names the algorithm, and RFC 7515 section 4.1.1 says it MUST be present; typ can name the kind of token; kid is, in the words of section 4.1.4, a hint indicating which key was used.
The payload holds the claims. RFC 7519 section 4.1 registers seven claim names: iss (who issued the token), sub (who it is about), aud (who it is for), exp (when it expires), nbf (when it starts to be valid), iat (when it was issued) and jti (a unique identifier for the token).
None of them is intended to be mandatory in all cases; the RFC says applications should define which claims they use and when they are required.
The signature covers the header and the payload together, and the WSTG JSON Web Tokens test puts the consequence plainly: modifying any part of the JWT should cause the signature to be invalid and the token to be rejected by the server.
Signed is not encrypted. OWASP's JSON Web Token Cheat Sheet says a signed JWT provides integrity and authenticity but not confidentiality: the payload is only base64url encoded, so anyone who obtains the token can read every claim. RFC 9068, the profile for OAuth access tokens in JWT format, says the same in its privacy considerations: because JWT access tokens carry information by value, clients and potentially even end users can look directly inside the claims of an unencrypted token.
RFC 7519 section 12 says that when a JWT contains privacy-sensitive information, measures MUST be taken to prevent its disclosure to unintended parties, and calls leaving that information out the simplest way of minimising privacy issues. Put nothing in a signed token that you would not show the person holding it.
OWASP's Application Security Verification Standard (ASVS) 5.0 files JWTs under self-contained tokens: tokens that carry the data or claims a receiving service relies on to make security decisions, as distinct from a simple token holding only an identifier the service looks up locally. It names JWTs and SAML assertions as the most common examples, and says the security of the mechanism relies on validating the token's integrity and making sure it is valid for a particular context. That validation is the verifier's job, and the subject of this guide.
Four neighbouring guides take the rest. OAuth and OIDC security covers where tokens come from when someone clicks "Sign in with", including the ID token and its nonce. Session management covers what sign-out and "sign out everywhere" have to reach. Broken access control covers what the person named in a valid token may see and change once it is accepted.
Secrets exposure covers what to do when a key or secret, such as a signing key, turns up in code, history, bundles or logs.
What a verifier must decide before it trusts a token
RFC 7519 section 11.1 sets the principle: the contents of a JWT cannot be relied upon in a trust decision unless they have been cryptographically secured and bound to the context the decision needs, and the keys used will typically need to be verifiably under the control of the party named as the issuer.
Section 7.2 lists the validation steps and says that if any of them fails, the JWT MUST be rejected. For an API that receives JWT access tokens, RFC 9068 section 4 turns this into checks the resource server MUST make: the token type, the issuer, the audience, the signature with keys the authorisation server provides, a refusal of alg none, and expiry, with some small leeway for clock skew allowed.
Combined with RFC 8725, the IETF's JSON Web Token Best Current Practices, and chapter V9 of ASVS 5.0, that comes to eleven decisions. They are numbered here in the order the suite's fixed verifier makes them. Each is answered from the verifier's own configuration; the token supplies only the values being checked.
- D1 Format: three base64url parts, with a JSON object in the header and the claims.
- D2 Header parameters: only the ones the verifier understands, so a key carried in the token is never used.
- D3 Token type: typ says this is the kind of token the API accepts.
- D4 Issuer: iss exactly matches an issuer the API is configured to trust.
- D5 Algorithm: alg equals the algorithm set in code for that issuer.
- D6 Key: chosen by kid from that issuer's configured keys, and from nowhere else.
- D7 Signature: checked with that key over the header and payload.
- D8 Required claims: every claim the API relies on is present.
- D9 Time: not expired and not before its start, within a small, stated leeway.
- D10 Audience: aud names this API.
- D11 Revocation: neither the token nor every token its user held before a cut-off has been revoked.
Why a token that chooses its own algorithm or key has passed no check
Anyone can write a JWT header.
RFC 8725 section 2.1 explains that signed JWTs carry an explicit indication of the signing algorithm, the alg header parameter, to allow cryptographic agility, and that this, in conjunction with design flaws in some libraries and applications, has led to several attacks.
If the verifier takes the algorithm or the key from the header, the person who made the token chose how it would be checked, and a check whose terms the sender sets proves nothing.
RFC 7519 section 6 defines an Unsecured JWT: alg set to none and an empty signature, for cases where something other than the JWT protects its content. RFC 8725 section 2.1 records the attack: an attacker can change the algorithm to none, and some libraries would trust this value and validate the JWT without checking any signature.
RFC 7518 section 3.6 says implementations MUST NOT accept Unsecured JWSs by default and that applications MUST NOT signal acceptance of them at a global level.
For JWT access tokens, RFC 9068 section 4 says the resource server MUST reject any JWT whose alg is none, and ASVS 5.0 requirement 9.1.2, at Level 1, says the algorithm allowlist must not include None.
A library default can open this door. The advisory for CVE-2022-23540 (GHSA-qwph-4952-7xr6) in the jsonwebtoken package for Node.js, published on 21 December 2022 and rated moderate, says that in versions up to 8.5.1, when a token with no signature was received, calling jwt.verify() with no algorithms specified and a falsy secret or key could bypass signature validation, because it defaulted to the none algorithm.
The vendor's advisory lists versions up to 8.5.1 as affected and 9.0.0 as the patched version, which removes the default support for none. The GitHub Advisory Database entry lists CWE-287, CWE-327 and CWE-347; the vendor's page lists no CWEs.
RFC 8725 section 2.1 describes the second attack. A token's alg is changed from RS256, an RSA signature, to HS256, an HMAC, and some libraries would then try to validate it using HMAC-SHA256 with the RSA public key as the HMAC shared secret.
A public key is meant to be shared: OWASP's JWT cheat sheet notes that because it does not need to be secret, it can easily be distributed, for example by publishing it at a public HTTPS address.
Anyone holding it can compute an HMAC such a verifier accepts. The cheat sheet calls this key confusion or algorithm confusion.
The jsonwebtoken package had a form of this too. Its advisory for CVE-2022-23541 (GHSA-hjrf-2m68-5959), published on 21 December 2022 and rated moderate, says versions up to 8.5.1 could be misconfigured so that a poorly implemented key retrieval function verified tokens with a different algorithm and key combination than the one used to sign them: tokens signed with an asymmetric public key could be verified with a symmetric HS256 algorithm, which can lead to successful validation of forged tokens.
It says applications were affected if they supported both symmetric and asymmetric keys in jwt.verify() with the same key retrieval function, and the issue is fixed in jsonwebtoken 9.0.0. The GitHub Advisory Database entry lists CWE-287 and CWE-1259; the vendor's page lists no CWEs.
One rule closes both attacks. RFC 8725 section 3.1 says libraries MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other, and that each key MUST be used with exactly one algorithm, checked when the cryptographic operation is performed. Section 3.2 says applications MUST only allow cryptographically current algorithms that meet their security requirements, and RFC 7515 section 5.2 says that unless the algorithm used is acceptable to the application, it SHOULD consider the JWS invalid even when it validates.
ASVS 5.0 requirement 9.1.2, at Level 1, asks for an allowlist of algorithms for each context, ideally only symmetric or only asymmetric ones, with additional controls against key confusion where both must be supported.
The suite's fixed verifier holds one algorithm per issuer, written in code, and refuses fixtures F03 and F04 at that step.
A JWS header can do more than name an algorithm. RFC 7515 defines jwk (section 4.1.3), the public key itself, embedded in the header; jku (section 4.1.2), a URL for a set of keys; x5u (section 4.1.5), a URL for a certificate; and kid.
Section 6 says these parameters MUST be integrity protected if the information they convey is used in a trust decision, unless the only information used in that decision is a key, and Appendix D, which illustrates ways to select a key, includes making trust decisions about the keys found: signatures made with keys not meeting the application's trust criteria would not be accepted.
A key read from the token was chosen by whoever made the token. OWASP's JWT cheat sheet says an attacker can include their own public key in jwk, or point jku or x5u at a key set or certificate they host, and sign with the matching private key, and that a verifier which trusts the key it has just read from the token accepts the forgery.
RFC 8725 section 3.10 adds that blindly following a jku or x5u URL could result in server-side request forgery, which applications SHOULD protect against, for example with an allowlist of locations, and that applications should validate or sanitise kid so that a key lookup does not create SQL or LDAP injection.
ASVS 5.0 requirement 9.1.3, at Level 1, asks that key material comes from trusted, pre-configured sources for the token issuer, with headers such as jku, x5u and jwk validated against an allowlist of trusted sources.
The suite's fixed verifier goes a step further and refuses any header parameter other than alg, typ and kid, which is how fixture F05, signed with an outsider's key carried in its own jwk header, is stopped. Refusing every other parameter is the suite's own, stricter choice.
RFC 7519 section 7.2 step 5 has the verifier check that the header holds only parameters whose syntax and semantics it understands and supports, or that are specified as being ignored when not understood.
Trusting more than one issuer creates a quieter version of the same problem. RFC 8725 section 3.8 says that when a JWT contains an iss claim, the application MUST validate that the keys used belong to that issuer and MUST reject the JWT if they do not.
OWASP's JWT cheat sheet describes how this fails in practice: a verifier that looks up the key by kid across the union of several trusted issuers' key sets will accept a token whose iss names one issuer and whose kid names a key belonging to another.
Its advice is to select the verification key from the set bound to the validated iss, and never to verify against a union of keys from several issuers.
In the suite, the flawed verifier keeps the production and staging keys in one table found by kid. Fixture F06 names the production issuer but is signed with the staging key, and the fixed verifier refuses it because that kid is not among the keys configured for production.
If anyone on your team can mint tokens in staging, this check and the issuer check described below are the ones that refuse those tokens in production.
RFC 8725 describes itself as a point-in-time statement and advises readers to look for updates. When this page was reviewed, the IETF datatracker listed draft-ietf-oauth-rfc8725bis-10, also titled JSON Web Token Best Current Practices, as an active Internet-Draft of the oauth working group: latest revision 21 August 2026, IESG state RFC Ed Queue, RFC Editor status "blocked: Author Input Required".
The draft says that, if approved, it obsoletes RFC 8725, and it adds threats found since, among them checks that blocked the string none but read alg case-insensitively, so an attacker could change alg to noNE and bypass the check.
It also says libraries should use allowlists for critical parameters such as alg instead of blocklists. The draft itself says Internet-Drafts should be cited only as work in progress, and the datatracker lists nothing that updates or obsoletes RFC 8725, so RFC 8725 remains the published practice. RFC 7515 section 4.1.1 already makes alg a case-sensitive string.
A valid signature does not mean the token is meant for you
A signature tells you who made the token, within limits: RFC 7515 section 10.5 notes that validating a MAC only shows the message came from one of the parties holding the shared key.
It says nothing about whether this API was the intended recipient, whether the token is the right kind, or whether it is still in date. RFC 8725 section 2.7 calls the result a substitution attack: a token given legitimately to one recipient is presented to another for which it was not intended, and if that is not caught, the attacker can gain access to resources it is not entitled to. Five checks deal with it.
- Issuer. RFC 9068 section 4 says the issuer identifier MUST exactly match the iss claim, and RFC 7519 compares such values as case-sensitive strings with no transformations. The WSTG JSON Web Tokens test warns that a prefix or substring comparison in place of exact equality can let a token from a lower-trust tenant or environment through. Fixture F07, a genuine token from the staging sign-in service, tests it.
- Audience. RFC 7519 section 4.1.3 says that when aud is present and the recipient does not identify itself with a value in it, the JWT MUST be rejected. RFC 8725 section 3.9 says that where one issuer issues JWTs for more than one relying party, the JWT MUST contain aud and the relying party MUST reject it if the audience is missing or not associated with it. ASVS 5.0 requirement 9.2.3, at Level 2, asks that the service only accepts tokens intended for use with it, and says that for JWTs this can be achieved by validating aud against an allowlist defined in the service. RFC 9700 section 2.3 says access tokens SHOULD be audience-restricted, and that a resource server MUST refuse to serve a request whose access token was not meant for it. F08, a production token issued for the billing API, tests it.
- Token type. RFC 8725 section 2.8 calls confusion between kinds of JWT cross-JWT confusion and says that where it could occur, mitigations MUST be employed; section 3.11 recommends explicit typing through the typ header for new uses. RFC 9068 section 4 says a resource server MUST verify that typ is at+jwt or application/at+jwt and reject any other value, and its section 5 explains that this helps tell JWT access tokens from OpenID Connect ID Tokens, whose layout is very similar. ASVS 5.0 requirement 9.2.2, at Level 2, asks the receiving service to validate that a token is the correct type and meant for the intended purpose before accepting its contents, and gives as an example that only access tokens can be accepted for authorisation decisions and only ID Tokens used for proving user authentication. F09 presents an ID token to the API.
- Time. RFC 7519 section 4.1.4 says a JWT MUST NOT be accepted for processing on or after its exp time, and section 4.1.5 says the same before its nbf time. Both let implementers provide some small leeway, usually no more than a few minutes, to account for clock skew. ASVS 5.0 requirement 9.2.1, at Level 1, asks that where a token carries a validity time span, nbf and exp are verified. The 60 seconds the suite allows is its own choice, so F11, expired 30 seconds ago, is accepted, while F10, expired ten minutes ago, and F12, not valid for another ten minutes, are refused.
- Required claims. A check on an absent claim passes nothing. RFC 7519 leaves every registered claim optional and the choice of required ones to the application, and RFC 9068 section 2.2 requires iss, exp, aud, sub, client_id, iat and jti in every JWT access token. The fixed verifier refuses a token with no exp (F13) rather than treating it as one that never expires.
Revocation, short lifetimes and refresh tokens
A self-contained token carries its own validity, so deleting a record on the server does not end it.
ASVS 5.0 says that for self-contained tokens, additional measures are required to revoke or block them, as they may otherwise remain valid until expiration. Its requirement 7.4.1, at Level 1, asks that once termination is triggered the application disallows any further use of the session, and says applications using self-contained tokens will need a solution such as maintaining a list of terminated tokens, disallowing tokens produced before a per-user date and time, or rotating a per-user signing key.
The suite tests the first two. The revoked list uses jti, which RFC 7519 section 4.1.7 says provides a unique identifier for the JWT and can be used to prevent replay. OWASP's JWT cheat sheet suggests keying such a deny list on jti and iss together, and warns that using the raw token or a hash of it as the key is not safe, because an attacker holding a revoked token might produce another representation of it that still passes the signature check.
F14 is a token whose jti is on the list.
The per-user cut-off is what a "sign out everywhere" button sets: F15 was issued before user-2002's cut-off and is refused, while F16, issued after it, is accepted, so the cut-off ends old tokens without locking the user out.
Every revocation check is a lookup on each request, which is the state a self-contained token was meant to avoid; the OWASP cheat sheet says that with a deny list, user sessions won't be completely stateless anymore. Short lifetimes are the other half.
RFC 6750 section 5.3 says token servers SHOULD issue short-lived bearer tokens, one hour or less, particularly to clients that run within a web browser, because this can reduce the impact of a leak. RFC 9700 section 4.14 says refresh tokens add to OAuth's security because they let the authorisation server issue access tokens with a short lifetime and reduced scope, reducing the potential impact of access token leakage.
Section 2.2.2 says refresh tokens for public clients MUST be sender-constrained or use refresh token rotation, and section 4.14.2 says authorisation servers MAY revoke refresh tokens automatically after a security event such as a password change or a logout at the authorisation server.
Revoking a refresh token stops new access tokens; it does nothing to one already issued. Unless the API checks a revocation list or a cut-off, an access token stays usable until its exp, so its lifetime is the longest a revocation can take to reach the API. Choose that lifetime with this in mind, and check revocation on the API for actions where waiting it out is not acceptable.
Where a browser should keep a token
The sources set limits rather than a single answer.
RFC 6750 section 5.3 says implementations MUST NOT store bearer tokens in cookies that can be sent in the clear, that implementations which do store them in cookies MUST take precautions against cross-site request forgery, and that bearer tokens SHOULD NOT be passed in page URLs.
OWASP's HTML5 Security Cheat Sheet says not to store session identifiers in local storage, because the data is always accessible by JavaScript, and that cookies can mitigate this risk with the HttpOnly flag; it also says a single cross-site scripting flaw can be used to steal all the data in local storage.
MDN's Set-Cookie reference says HttpOnly forbids JavaScript from accessing the cookie, and that such a cookie is still sent with requests that JavaScript starts, such as fetch().
ASVS 5.0 does not rule browser storage out. Its requirement 14.3.3, at Level 2, asks that localStorage, sessionStorage, IndexedDB and cookies hold no sensitive data, with the exception of session tokens, and requirement 14.3.1, at Level 1, asks that authenticated data is cleared from client storage after the session ends.
Read together: script on the page can read a token kept in localStorage, and cannot read one kept in an HttpOnly cookie but can still make requests that carry it, and neither belongs in a URL.
Either way the token depends on the page being free of injected script. The cookie security guide covers the attributes a token cookie needs, and the XSS guide covers keeping injected script off the page.
When a plain server-side session is the simpler choice
OWASP's JWT cheat sheet opens its considerations with a question: whether JWTs are really necessary for your use case.
It says JWTs are often suggested for stateless user sessions and that this usage is frowned upon, and explains why: user sessions need a way to be invalidated, a deny list provides one, and with a deny list the sessions are no longer completely stateless, which might defeat the benefit. It suggests considering a plain session system instead.
ASVS 5.0 draws the same line from the other side. Chapter V9 separates self-contained tokens from simple tokens that contain only an identifier the service looks up locally, and requirement 7.4.1 says that for reference tokens or stateful sessions, terminating a session means invalidating the session data at the application backend. On a server-side session that is one delete, effective on the next request.
This page's view: if one web application talks to its own backend, a server-side session with an opaque identifier in a cookie gives you revocation and sign out everywhere without the algorithm, key and claim decisions above, though it has rules of its own for issuing, renewing and ending the identifier.
JWT access tokens earn their extra decisions where an API accepts tokens from a separate issuer, which is the case RFC 9068 describes: authorisation servers and resource servers from different vendors issuing and consuming access tokens in an interoperable way.
How to prove your verifier makes each decision
A verifier is easy to test because you control both ends.
Mint tokens with keys your test generates, give each one to your verifier, and assert both the outcome and the reason. Make each fixture break exactly one decision and leave the rest valid, so a refusal can only come from the check you meant to test, and put a few just inside a limit, so you also see the verifier accept what it should.
Do this against your own verifier in your own test environment, not by sending crafted tokens to a service you do not own or are not authorised in writing to test.
OWASP's Web Security Testing Guide has a JSON Web Tokens test, WSTG-SESS-10, in its latest edition, which the site says represents the latest contributions to the guide and may frequently change. v4.2, the stable release, lists nine session management tests, 4.6.1 to 4.6.9, and none of them covers JWTs.
WSTG-SESS-10's objectives are to determine whether JWTs expose sensitive information and whether they can be tampered with or modified. Its tests include modifying the body of a token without changing the header or signature to see whether the application accepts it, the none algorithm, HMAC and public key confusion, a public key embedded in the jwk header, kid manipulation, jku and x5u injection, and a token issued for one service, tenant or environment replayed against another.
Its remediation list includes using a secure and up to date library, checking that the signature is valid and uses the expected algorithm, and always validating exp, nbf, iss and aud.
MITRE's catalogue names the weakness. In CWE version 5.0, CWE-347, Improper Verification of Cryptographic Signature, is a Base weakness in which the product does not verify, or incorrectly verifies, the cryptographic signature for data, and MITRE files it under its OWASP Top Ten 2025 category for A04:2025 Cryptographic Failures.
Its parent, CWE-345, Insufficient Verification of Data Authenticity, is a Class weakness in which the product does not sufficiently verify the origin or authenticity of data in a way that causes it to accept invalid data.
For an evidence trail, record which ASVS 5.0 requirement each fixture exercises: 9.1.1 for the signature, 9.1.2 for the algorithm allowlist, 9.1.3 for key sources, 9.2.1 for exp and nbf, 9.2.2 for the token type, 9.2.3 for the audience and 7.4.1 for revocation. The decision table in the asset does this row by row.
Settings to check when a library does the verifying
Use a secure, up-to-date library to handle JWTs; it is the first point in WSTG-SESS-10's remediation list.
A library still makes only the decisions you configure, and its documentation says what happens when you leave an option out. The documentation of two Node.js libraries shows the pattern.
- jsonwebtoken:its README says that when the algorithms option is not specified, a default list is used based on the type of key provided: HS256, HS384 and HS512 for a secret, and RS256, RS384 and RS512 for an RSA key. Of the audience option it says "if you want to check audience (aud), provide a value here"; issuer is optional, and clockTolerance sets the seconds to tolerate when checking nbf and exp. jwt.decode() returns the payload without verifying the signature, and the README warns not to use it for untrusted messages and to treat a decoded payload from an untrusted source like any other user input. For the two advisories above, the vendor advisories list versions up to 8.5.1 as affected and 9.0.0 as patched.
- jose:its documentation says the algorithms option defaults to all algorithms applicable to the key or secret, and that unsecured JWTs (alg none) are never accepted. Its audience, issuer and subject options each set an expected value and require the claim to be present, typ does the same for the header parameter, requiredClaims names further claims that must be present, and clockTolerance applies to nbf and exp, and to iat when maxTokenAge is set.
Write the decisions into your configuration
In both libraries the algorithm list, the issuer, the audience and the leeway are values you pass. Pass them even where a default happens to match, so each decision is written in your own code; resolve keys per issuer rather than from one shared list; require the claims you rely on; and then run fixtures like the suite's against the verifier as configured. The tests check the configuration you deployed, not the library in general.
Running the verification suite on your own machine
The suite in the asset is an illustration, for learning and for testing a verifier you own.
It has five files and uses only modules that ship with Node.js: node:crypto makes three RSA key pairs when it starts, signs tokens and checks signatures, and node:test runs the regression test. Nothing is installed, no token, key or secret comes from outside the run, and nothing contacts another machine.
The issuers, the API and the users are invented. It was written and run on Node.js 26.0.0, the only version it was run on, and every output in the asset was copied from that run.
The flawed verifier is not a straw man: it checks signatures, so it refuses the tampered token in F02. Its mistakes are the ones described above, each marked FLAWED in the code: it takes the algorithm and the key from the header, keeps the production and staging keys in one table found by kid, and checks no claim.
The fixed verifier makes decisions D1 to D11 in order, each from its own configuration, and reports the first one a token fails.
- Save the five files into an empty folder and open a terminal there.
- Run node run-suite.mjs. For each of the sixteen fixtures it prints how the token was made, its header and claims, the token shortened to its first 16 and last 6 characters, the expected decision, and what each verifier decided and why. The keys and each jti are new on every run, so the end of each token differs every time; everything else repeats. The flawed verifier makes 4 of the 16 expected decisions and the fixed verifier all 16.
- Run node jwt-verifier.test.mjs. Node's built-in test runner runs the sixteen fixtures against the fixed verifier and all pass. Run node jwt-verifier.test.mjs flawed and twelve fail, each with what was expected and what happened. The Node.js test runner documentation says the process exit code is set to 1 when any test fails, so a pipeline step running the test fails too.
Pointing the fixtures at your own verifier
Keep the minter and the fixtures, and change runVerifier so it calls your verifier, configured as in production except that its trusted key for your issuer is the suite's production public key. Keep the staging and outsider keys out of that configuration: they exist to be refused.
Give your verifier the suite's fixed clock as its current time, which the jsonwebtoken README calls clockTimestamp and the jose documentation calls currentDate. Run it in your test environment and in the pipeline that deploys your API, never against a live service.
Where an outside test fits
Your own fixtures cover the verifier you know about.
A Clever Ops web application and API penetration test covers authentication and sessions, what each role can see and change, and the API called directly rather than only through the screens; for an API that accepts JWTs, that includes how it checks the tokens it receives. Each finding comes with evidence, a fix written for your stack and the criteria the retest will use.
If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
It is the set of checks that decide whether a JSON Web Token can be trusted: that the algorithm and key come from the verifier's configuration rather than the token, that the signature is valid, that the token was issued by a trusted issuer for this service, is the right kind and is within its validity time, and that it has not been revoked. RFC 7519 says a JWT's contents cannot be relied on in a trust decision unless they are cryptographically secured and bound to the context the decision needs.
Yes, if it is only signed. OWASP's JWT cheat sheet says the payload of a signed JWT is only base64url encoded, not encrypted, so anyone who obtains the token can read every claim. Leave sensitive information out of the token; the cheat sheet suggests encryption only when the claims must travel with the token to a party that cannot look them up with the issuer.
An attack on a verifier that lets the token's alg header choose the algorithm. RFC 8725 describes an RS256 token changed to HS256 so that some libraries validate it as an HMAC, using the RSA public key as the shared secret. Because the public key is public, anyone can then make a token such a verifier accepts. Fix the accepted algorithm for each issuer in your verifier's configuration. RFC 8725 section 3.1 says libraries MUST let the caller specify the supported algorithms and MUST NOT use any other.
For a JWT access token, RFC 9068 requires iss, exp, aud, sub, client_id, iat and jti, and says the resource server MUST check that typ is at+jwt or application/at+jwt, that iss exactly matches the issuer, that aud includes the resource server and that exp has not passed. Check nbf too when it is present, as ASVS 5.0 requirement 9.2.1 asks, and refuse a token that lacks a claim you rely on.
By checking something on each request, because the token may stay valid until it expires. ASVS 5.0 requirement 7.4.1 gives three examples: a list of terminated tokens, refusing tokens produced before a per-user date and time, and rotating a per-user signing key. Short lifetimes limit how long an unrevoked token works; RFC 6750 says token servers SHOULD issue bearer tokens lasting one hour or less.
OWASP's HTML5 Security Cheat Sheet says not to store session identifiers in local storage, because the data is always accessible by JavaScript, and that cookies can mitigate this risk with the HttpOnly flag. RFC 6750 says bearer tokens MUST NOT go in cookies that can be sent in the clear and that tokens kept in cookies need precautions against cross-site request forgery. ASVS 5.0 allows session tokens in browser storage. Either way, the token depends on the page being free of injected script.
Not by default. OWASP's JWT cheat sheet says JWTs used for user sessions need a way to be invalidated, that a deny list means the sessions are no longer completely stateless, and that a plain session system is worth considering. JWT access tokens suit an API that accepts tokens from a separate authorisation server. For one application talking to its own backend, this page recommends a server-side session.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.