Test JWT handling: expired, tampered and wrong-audience tokens

A JSON Web Token carries its own expiry, issuer, audience and claims, and the API decides whether to trust it. That decision is code, and code has bugs: an API that accepts a token expired an hour ago, one with "alg": "none", or one minted for a different service. These are cheap to test once you can read and build tokens in a script.

Read a token in a script

A JWT is three base64url parts: header, payload, signature. The first two are just JSON:

JavaScript
const CryptoJS = require('crypto-js');

function decodePart(part) {
  const base64 = part.replace(/-/g, '+').replace(/_/g, '/');
  const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
  return JSON.parse(CryptoJS.enc.Base64.parse(padded).toString(CryptoJS.enc.Utf8));
}

const token = pm.response.json().access_token;
const claims = decodePart(token.split('.')[1]);

Decoding is not verifying: anyone can read a JWT. Never put secrets in one, and test that your API doesn't either.

Test what the login gives you

JavaScript
const now = Math.floor(Date.now() / 1000);

pm.test('expires within an hour', () => {
  pm.expect(claims.exp - now).to.be.within(60, 3600);
});
pm.test('issued by us, for this API', () => {
  pm.expect(claims.iss).to.equal(pm.environment.get('issuer'));
  pm.expect(claims.aud).to.include(pm.environment.get('audience'));
});
pm.test('no personal data in the token', () => {
  pm.expect(claims).to.not.have.property('email');
  pm.expect(claims).to.not.have.property('phone');
});

pm.environment.set('token', token);
pm.environment.set('tokenExp', String(claims.exp));

Adjust the claims to your design. The point is that a change to token lifetime or contents shows up as a failing test, not a surprise in production.

Send tokens that must be refused

Keep a few bad tokens as secret environment variables, generated once with your auth server's test keys or a tool like jwt.io:

VariableWhat's wrong
expiredTokenexp in the past, valid signature
noneTokenheader {"alg":"none"}, no signature
tamperedTokena valid token with one payload character changed, original signature
otherKeyTokenvalid structure, signed with a key your API doesn't trust
wrongAudTokenvalid, but aud is another service
futureTokennbf an hour from now

Then one request per token in a folder, and one folder test:

JavaScript
pm.test('rejected', () => pm.response.to.have.status(401));
pm.test('says why, without leaking details', () => {
  const challenge = pm.response.headers.get('WWW-Authenticate') || '';
  pm.expect(challenge).to.include('Bearer');
});

You can build the tampered one in a pre-request script instead of storing it:

JavaScript
const [header, payload, signature] = pm.environment.get('token').split('.');
const swapped = payload.slice(0, -1) + (payload.endsWith('A') ? 'B' : 'A');
pm.variables.set('tamperedToken', [header, swapped, signature].join('.'));

Don't let a long run expire

A collection run that takes longer than a token's lifetime fails halfway with 401s that look like real bugs. Check the expiry before each request, and log in again when it's close. In the collection's pre-request script:

JavaScript
const exp = Number(pm.environment.get('tokenExp') || 0);
if (exp - Math.floor(Date.now() / 1000) < 60) {
  console.log('Token expires in under a minute; the next Login request will refresh it.');
}

Scripts can't send requests of their own, so the refresh itself is a request: put a Login (or Refresh token) request at the start of each folder that runs long, so the token is never older than one folder's run.