JWT and testing tokens
A JWT is a signed string header.payload.signature, where the first two parts are JSON in Base64URL and the signature guarantees the token was not altered. The payload is only encoded, not encrypted, so secrets do not belong there. The server must check the signature, exp and allowed algorithms itself instead of trusting the token's header (the alg: none attack). Expired and forged tokens must yield 401 with WWW-Authenticate.
API · Authorization
The token expired long ago, yet the API answers 200. What does the server actually check?
A tester takes a token from yesterday's run, sends a request to /v1/me and gets 200 with a profile. The token was supposed to live 15 minutes. The developer says: "The signature is valid." True, a signature does not change with time, while checking the exp field is a separate step that is easy to forget. To test tokens you need to know what they consist of and which part the server must check itself.
Below: how a JWT is built, what in it is trusted and what is not, and a set of negative cases that catches the typical defects.
How a JWT is built
A signed JSON Web Token (JWS, RFC 7519) is a string of three parts joined by dots: header.payload.signature. Each of the first two parts is JSON in Base64URL encoding, the third is a signature over the first two. An encrypted variant (JWE) exists but is rare.
// header
{ "alg": "HS256", "typ": "JWT" }
// payload (claims)
{ "sub": "42", "role": "user", "iat": 1764496400, "exp": 1764497300 }
// signature = HMAC-SHA256(base64url(header) + "." + base64url(payload), secret)
Three parts of a JWT
Why it is designed this way. A JWT lets the server skip the database on each request: everything needed (who this is, the role, until when the token is valid) is inside the token, and the signature guarantees nobody changed it. Two consequences follow, and they define the tests. First, Base64URL is an encoding, not encryption: passwords and sensitive data do not belong in the payload, because anyone holding the token can read them. Second, trust rests on the signature, so the server must verify it itself, check exp itself, and keep a list of allowed algorithms (in the library configuration, not taken from the token header).
The main claims from RFC 7519: exp (when the token stops being valid, seconds since 1970), iat (when issued), nbf (not before), sub (who), iss (who issued it), aud (for whom). A role or permissions are usually extra, custom claims. The token travels in the header Authorization: Bearer <token>.
Access and refresh tokens
Access token
Lives minutes. Goes with every API request. If stolen, the damage is limited by time.
Refresh token
Lives days or weeks. Goes only to the token endpoint. It is revoked and rotated on the server.
Example: an expired token and an alg none token
We suspect the server looks only at the signature. We check with what it must reject. A token with "alg": "none" (no signature) and admin rights must get 401. Here is a response that is a serious defect (the token is shortened to its structure, the full string looks the same):
GET /v1/me HTTP/1.1
Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiI0MiIsInJvbGUiOiJhZG1pbiJ9.
HTTP/1.1 200 OK
Content-Type: application/json
{ "id": "42", "role": "admin" }
The server believed the token header, which is controlled by the client, and accepted an "unsigned" token. This is a well-known library vulnerability, closed by an explicit list of allowed algorithms. A set of negative cases catches it together with an expired and a forged token. The test helper builds tokens itself, because broken ones are exactly what we need:
import { createHmac } from 'node:crypto';
import { test, expect } from '@playwright/test';
const b64 = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64url');
function forge(payload: object, alg = 'HS256') {
const head = b64({ alg, typ: 'JWT' });
const body = b64(payload);
if (alg === 'none') return head + '.' + body + '.';
const sig = createHmac('sha256', 'wrong-secret')
.update(head + '.' + body).digest('base64url');
return head + '.' + body + '.' + sig;
}
const now = Math.floor(Date.now() / 1000);
const admin = { sub: '42', role: 'admin', exp: now + 600 };
const cases = [
{ name: 'expired', token: forge({ sub: '42', exp: now - 60 }) },
{ name: 'wrong signature', token: forge(admin) },
{ name: 'alg none', token: forge(admin, 'none') },
{ name: 'truncated', token: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIi' },
];
for (const c of cases) {
test('GET /v1/me with a ' + c.name + ' token', async ({ request }) => {
const res = await request.get('/v1/me', {
headers: { Authorization: 'Bearer ' + c.token },
});
expect(res.status()).toBe(401);
expect(res.headers()['www-authenticate']).toMatch(/^Bearer/);
});
}
Every case expects 401 and a WWW-Authenticate: Bearer header, which HTTP requires in a 401 response. The signature in the "wrong signature" case is made with a foreign secret: this is the same as changing the role in the payload without re-signing, because the signature no longer matches the content. Three more cases need no helper: an empty header, a scheme other than Bearer, and a token from another environment (staging on prod).
Limits and alternatives
- A stateless JWT means issuing is easy and revoking is hard: after logout or a password change it formally works until
exp. A service either keeps a list of revoked tokens, or has a very shortexpand revokes the refresh token. The policy comes from the contract, and the test checks exactly it. - Server clocks can drift, so many services allow a small leeway on
expandnbf. Test the time boundary with a margin (a token that expired an hour ago), not by one second. - Opaque tokens are checked by the server with a store lookup or an introspection endpoint. They are easy to revoke but add a call. This is an alternative to JWT, not a mistake.
- Symmetric (HS256) tokens need a shared secret, asymmetric (RS256, ES256) ones can be verified with a public key. For a client that only reads the payload, there is no difference.
Common mistakes
- Checking only "a valid token gives 200". Negative cases (
exp, signature, algorithm) hold almost all authorization defects. - Taking an expired token from yesterday's run. The test depends on time and becomes unstable. The token is built in the test or a fresh one is obtained by login.
- Treating the payload as secret. Anyone can decode it (for example on jwt.io), so a password or a card number there is a defect.
- Mixing up 401 and 403. A missing or broken token is 401, a valid token without rights is 403.
Check yourself
A test changes the role in the payload from user to admin but keeps the old signature. The server returns 200 and admin data. What is the defect?
Answer
The server does not verify the signature (or trusts the payload before verifying). The signature is computed over the header and the payload, so any change to the payload must break it, and the response must be 401.
After logout the same access token still gives 200 for 5 minutes. Is that a bug?
Answer
It depends on the contract. For a JWT without a revocation list it is expected until exp. It is a bug if the documentation promises immediate invalidation, or if the refresh token still works after logout. Both are checked.
exp, iss/aud and the allowed algorithms itself, not trust the token header (the alg none attack). I generate broken tokens with a helper and check 401 together with WWW-Authenticate. Separately I find out the revocation policy: after logout or a password change a stateless token lives until exp.