← Back to Node.js, page 8

nodejs-0156 · Easy fresher

How do you verify a JWT correctly in Node.js: algorithm allowlist, expiry, issuer and audience, and what is the 'alg none' attack?

jwt.verify checks the signature and the standard claims, but you must pass the algorithms you accept, plus the issuer and audience you expect. Without an allowlist, an attacker can forge a token with alg none or switch a public key algorithm to HMAC. jwt.decode only reads the payload and verifies nothing. Keep access tokens short, use strong secrets or key pairs, and handle TokenExpiredError separately.

Full answer

Verify, do not decode

  • jwt.decode(token) returns the payload without checking anything. Never use it to make a security decision.
  • jwt.verify(token, secretOrKey, options) checks the signature, exp (expiry), nbf (not before), and the options you pass.

Options that matter

  • algorithms: ['HS256'] (or ['RS256'] for public key setups). If you leave it out, the library decides from the header, which the attacker controls. The old attacks: alg none (a token with no signature) and algorithm confusion (a token signed with HMAC using the public key as the secret).
  • issuer and audience: check that the token was made by your auth service for your API. Tokens from another system with the same secret should not work.
  • clockTolerance of a few seconds helps with small clock differences.
  • maxAge as an extra limit on token age.

Good practice

  • Use a long random secret for HS256 (32 bytes or more) from the environment, or an asymmetric key pair (RS256, ES256, EdDSA) so that other services can verify without being able to sign. Publish public keys through a JWKS endpoint and use a kid header for rotation.
  • Short expiry (5 to 15 minutes).
  • Return the same 401 for all verification failures. Log the specific error internally (TokenExpiredError, JsonWebTokenError, NotBeforeError).
  • Do not put sensitive data in the payload; it is only encoded.
  • Libraries: jsonwebtoken, jose (also supports Web Crypto and JWKS helpers).
javascript
const jwt = require('jsonwebtoken');
const crypto = require('node:crypto');

const secret = crypto.randomBytes(32).toString('hex');
const options = { algorithms: ['HS256'], issuer: 'school-auth', audience: 'school-api' };
const check = (label, token, opts = options, key = secret) => {
  try { console.log(label.padEnd(24), 'OK', JSON.stringify(jwt.verify(token, key, opts).sub)); }
  catch (err) { console.log(label.padEnd(24), 'rejected:', err.name + ' (' + err.message + ')'); }
};

const good = jwt.sign({ sub: 'asha' }, secret, { algorithm: 'HS256', issuer: 'school-auth', audience: 'school-api', expiresIn: '10m' });
check('valid token', good);

check('expired token', jwt.sign({ sub: 'asha', exp: Math.floor(Date.now() / 1000) - 60 }, secret, { issuer: 'school-auth', audience: 'school-api' }));
check('wrong audience', jwt.sign({ sub: 'asha' }, secret, { issuer: 'school-auth', audience: 'other-api' }));
check('wrong secret', jwt.sign({ sub: 'asha' }, 'another-secret', { issuer: 'school-auth', audience: 'school-api' }));

// Tampered payload: change the subject and keep the old signature.
const [h, , s] = good.split('.');
const forgedPayload = Buffer.from(JSON.stringify({ sub: 'admin', iss: 'school-auth', aud: 'school-api' })).toString('base64url');
check('tampered payload', `${h}.${forgedPayload}.${s}`);

// The alg none attack: a token without a signature.
const none = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url') + '.' + forgedPayload + '.';
check('alg none token', none);
check('alg none, no allowlist', none, { issuer: 'school-auth', audience: 'school-api' });

console.log('decode reads a forged token without complaint:', jwt.decode(none).sub);

A good token passes. Expired, wrong audience, wrong secret, tampered and unsigned tokens are all rejected. Install first with npm install jsonwebtoken (run here with jsonwebtoken 9.0.3). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): valid token OK "asha" expired token rejected: TokenExpiredError (jwt expired) wrong audience rejected: JsonWebTokenError (jwt audience invalid. expected: school-api) wrong secret rejected: JsonWebTokenError (invalid signature) tampered payload rejected: JsonWebTokenError (invalid signature) alg none token rejected: JsonWebTokenError (jwt signature is required) alg none, no allowlist rejected: JsonWebTokenError (jwt signature is required) decode reads a forged token without complaint: admin

Key points

  • verify checks the signature and claims; decode checks nothing.
  • Always pass an algorithms allowlist.
  • Check issuer and audience.
  • Use strong secrets or key pairs, with short expiry.
  • Return one generic 401 and log the detail.

Common mistakes

  • Using jwt.decode to decide who the user is.
  • Calling verify without an algorithms list.
  • Not checking audience and issuer.
  • Hard-coded or short secrets.
  • Returning different errors that help an attacker.

Follow-ups

  • What is algorithm confusion between RS256 and HS256?
  • How does a JWKS endpoint support key rotation?
  • Why use an asymmetric algorithm for microservices?

Tips

  • Say 'verify, never decode'.
  • Name alg none.
  • List issuer, audience, expiry.