Build a Minimal JWT Authentication Service
A small authentication service that issues HMAC-signed JSON Web Tokens, verifies them on protected routes, enforces expiry, and rejects tampered tokens with clear errors.
Project goal
Build an auth service that signs and verifies JWTs with HMAC-SHA256, protects routes with a bearer token, enforces expiry and issuer claims, and returns precise errors for each failure mode.
Final features
- Issue a signed token with subject, issuer, and expiry claims.
- Verify signature, expiry, and issuer on every protected request.
- Reject tampered payloads and wrong keys with specific error codes.
- Protect a route that returns the authenticated subject.
- Expose token issuance via a login endpoint.
Architecture
A claims module builds and validates the claim set; a signer produces and parses the compact JWS serialisation using node:crypto; a verifier checks the signature in constant time and then the time-based claims; and middleware attaches the subject to the request. No third-party JWT library is used so each step is visible.
Prerequisites
- Node.js 20 LTS or later
- Understanding of HMAC and base64url encoding
- Basic familiarity with HTTP bearer tokens
Dependencies
- node >=20 — node:crypto for HMAC and timing-safe comparison
- vitest ^2.1.0 — Sign, verify, and failure-mode tests
Directory structure
jwt-service/
├── src/
│ ├── base64url.js
│ ├── sign.js
│ ├── verify.js
│ ├── middleware.js
│ └── server.js
├── test/
│ ├── sign.test.js
│ └── verify.test.js
└── package.json
Phases
1. Base64url helpers
Encode and decode JSON to base64url without padding, matching the JWT serialisation exactly.
Files: src/base64url.js
export function encodeJson(value) {
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
}
export function decodeJson(segment) {
const json = Buffer.from(segment, 'base64url').toString('utf8');
return JSON.parse(json);
}Expected behavior: Encoding an object then decoding it returns the same object, and the output contains no +, /, or = characters.
2. Claim construction
Build a standard claim set with subject, issuer, issued-at, and expiry, and validate required claims on the way back.
Files: src/claims.js
export function buildClaims(subject, { issuer, ttlSeconds = 900, now = Date.now() }) {
const iat = Math.floor(now / 1000);
return { sub: subject, iss: issuer, iat, exp: iat + ttlSeconds };
}
export function validateClaims(claims, { issuer, now = Date.now(), clockSkew = 30 }) {
if (claims.iss !== issuer) return { ok: false, code: 'bad_issuer' };
const seconds = Math.floor(now / 1000);
if (typeof claims.exp !== 'number' || seconds > claims.exp + clockSkew) {
return { ok: false, code: 'expired' };
}
return { ok: true };
}Expected behavior: A token built with a 15-minute ttl is valid immediately, expired an hour later, and rejected with bad_issuer when the issuer differs.
3. Signing
Produce the compact JWS serialisation with an HMAC-SHA256 signature over the header and payload.
Files: src/sign.js
import { createHmac } from 'node:crypto';
import { encodeJson } from './base64url.js';
export function sign(payload, secret) {
const header = encodeJson({ alg: 'HS256', typ: 'JWT' });
const body = encodeJson(payload);
const data = header + '.' + body;
const signature = createHmac('sha256', secret).update(data).digest('base64url');
return data + '.' + signature;
}Expected behavior: Two calls with the same payload and secret produce identical tokens, and a different secret produces a different third segment.
4. Verification
Split the token, recompute the signature, compare it in constant time, then validate the claims.
Files: src/verify.js
import { createHmac, timingSafeEqual } from 'node:crypto';
import { decodeJson } from './base64url.js';
import { validateClaims } from './claims.js';
export function verify(token, secret, { issuer } = {}) {
const parts = token.split('.');
if (parts.length !== 3) return { ok: false, code: 'malformed' };
const data = parts[0] + '.' + parts[1];
const expected = createHmac('sha256', secret).update(data).digest();
const provided = Buffer.from(parts[2], 'base64url');
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
return { ok: false, code: 'bad_signature' };
}
const claims = decodeJson(parts[1]);
const check = validateClaims(claims, { issuer });
return check.ok ? { ok: true, claims } : check;
}Expected behavior: A valid token verifies, a token with one flipped payload byte returns bad_signature, and an expired token returns expired.
5. Protected route middleware
Extract the bearer token, verify it, and attach the subject to the request or return 401 with the specific code.
Files: src/middleware.js
import { verify } from './verify.js';
export function authenticate(req, { secret, issuer }) {
const header = req.headers.authorization ?? '';
const match = /^Bearer (.+)$/.exec(header);
if (!match) return { ok: false, status: 401, body: { error: 'missing_token' } };
const result = verify(match[1], secret, { issuer });
if (!result.ok) return { ok: false, status: 401, body: { error: result.code } };
return { ok: true, subject: result.claims.sub };
}Expected behavior: A request without a bearer header returns missing_token, a tampered token returns bad_signature, and a valid token yields the subject.
6. Server and tests
Wire a login endpoint and a protected endpoint, then cover signing, verification, and every failure code with tests.
Files: src/server.js
import { createServer } from 'node:http';
import { sign } from './sign.js';
import { buildClaims } from './claims.js';
import { authenticate } from './middleware.js';
const SECRET = process.env.JWT_SECRET ?? 'dev-only-secret';
const ISSUER = 'jwt-service';
const server = createServer((req, res) => {
if (req.url === '/login' && req.method === 'POST') {
const claims = buildClaims('user-1', { issuer: ISSUER });
return send(res, 200, { token: sign(claims, SECRET) });
}
if (req.url === '/me') {
const auth = authenticate(req, { secret: SECRET, issuer: ISSUER });
return auth.ok ? send(res, 200, { sub: auth.subject }) : send(res, auth.status, auth.body);
}
send(res, 404, { error: 'not_found' });
});
function send(res, status, body) {
res.writeHead(status, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
}
server.listen(process.env.PORT ?? 3000);
export { server };Expected behavior: Login returns a token, calling /me with that token returns the subject, and calling /me without it returns 401 missing_token.
Testing
Run npx vitest. Signing tests assert the token has three segments and that changing one byte of the payload invalidates it. Verification tests cover valid tokens, expired tokens, wrong-issuer tokens, and tokens signed with a different secret, each asserting a distinct error code. A timing test asserts the comparison uses the timing-safe function rather than string equality.
Troubleshooting
Valid tokens are rejected after a secret rotation
Expect verification to fail once the secret changes; support two accepted secrets during a rotation window keyed by a kid header, then retire the old one.
The signature check sometimes accepts tampered tokens
Never compare signatures with string equality; compare the decoded bytes with timingSafeEqual and check lengths first, which also avoids leaking position information.
Tokens appear valid immediately after expiry
Allow a small clock-skew allowance and account for it explicitly; rejecting at the exact second invites flaky failures between services with slightly different clocks.
Deployment
Run behind TLS and store the secret in a secrets manager, not in the repository. In a multi-service setting, publish the issuer and accepted algorithms so every verifier agrees on what a valid token means.
Known limitations
- HMAC means every verifier also holds the signing secret; asymmetric signing is the upgrade path when verifiers should not be able to mint tokens.
- There is no revocation list, so a stolen token stays valid until it expires.
Project overview
JWTs look simple and are easy to get subtly wrong. This project implements the compact serialisation from scratch so the signature, the encoding, and the time checks are each inspectable, and then pins the failure modes with tests.
The service issues tokens on login, verifies them on a protected route, and distinguishes an expired token from a tampered one or a wrong key through explicit error codes.
Signing is three base64url segments with an HMAC over the first two, which is the entire mechanism in a few lines:
import { createHmac } from 'node:crypto';
export function sign(payload, secret, { header = { alg: 'HS256', typ: 'JWT' } } = {}) {
const encodedHeader = encodeJson(header);
const encodedPayload = encodeJson(payload);
const data = encodedHeader + '.' + encodedPayload;
const signature = createHmac('sha256', secret).update(data).digest('base64url');
return data + '.' + signature;
}
Verification reverses the same steps and compares the signature with a timing-safe check, which is where a naive implementation leaks information.
Setup
This project deliberately uses node:crypto rather than a JWT package so the tutorial can show the signature bytes, the encoding, and the claim checks without indirection.
| Dependency | Version | Why it is here |
|---|---|---|
| node | >=20 | node:crypto for HMAC and timing-safe comparison |
| vitest | ^2.1.0 | Sign, verify, and failure-mode tests |
Create the project and install:
mkdir jwt-service && cd jwt-service
npm init -y
npm install -D vitest@^2.1.0
Configure package.json with the server entry and tests:
{
"name": "jwt-service",
"type": "module",
"scripts": {
"start": "node src/server.js",
"test": "vitest run"
}
}
Read the signing secret from an environment variable and never commit a default value; tests pass an explicit secret of their own.
Phase 1: Base64url helpers
Encode and decode JSON to base64url without padding, matching the JWT serialisation exactly. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.
export function encodeJson(value) {
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
}
export function decodeJson(segment) {
const json = Buffer.from(segment, 'base64url').toString('utf8');
return JSON.parse(json);
}
Acceptance for this phase: Encoding an object then decoding it returns the same object, and the output contains no +, /, or = characters.
Phase 2: Claim construction
Build a standard claim set with subject, issuer, issued-at, and expiry, and validate required claims on the way back. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.
export function buildClaims(subject, { issuer, ttlSeconds = 900, now = Date.now() }) {
const iat = Math.floor(now / 1000);
return { sub: subject, iss: issuer, iat, exp: iat + ttlSeconds };
}
export function validateClaims(claims, { issuer, now = Date.now(), clockSkew = 30 }) {
if (claims.iss !== issuer) return { ok: false, code: 'bad_issuer' };
const seconds = Math.floor(now / 1000);
if (typeof claims.exp !== 'number' || seconds > claims.exp + clockSkew) {
return { ok: false, code: 'expired' };
}
return { ok: true };
}
Acceptance for this phase: A token built with a 15-minute ttl is valid immediately, expired an hour later, and rejected with bad_issuer when the issuer differs.
Phase 3: Signing
Produce the compact JWS serialisation with an HMAC-SHA256 signature over the header and payload. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.
import { createHmac } from 'node:crypto';
import { encodeJson } from './base64url.js';
export function sign(payload, secret) {
const header = encodeJson({ alg: 'HS256', typ: 'JWT' });
const body = encodeJson(payload);
const data = header + '.' + body;
const signature = createHmac('sha256', secret).update(data).digest('base64url');
return data + '.' + signature;
}
Acceptance for this phase: Two calls with the same payload and secret produce identical tokens, and a different secret produces a different third segment.
Phase 4: Verification
Split the token, recompute the signature, compare it in constant time, then validate the claims. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.
import { createHmac, timingSafeEqual } from 'node:crypto';
import { decodeJson } from './base64url.js';
import { validateClaims } from './claims.js';
export function verify(token, secret, { issuer } = {}) {
const parts = token.split('.');
if (parts.length !== 3) return { ok: false, code: 'malformed' };
const data = parts[0] + '.' + parts[1];
const expected = createHmac('sha256', secret).update(data).digest();
const provided = Buffer.from(parts[2], 'base64url');
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
return { ok: false, code: 'bad_signature' };
}
const claims = decodeJson(parts[1]);
const check = validateClaims(claims, { issuer });
return check.ok ? { ok: true, claims } : check;
}
Acceptance for this phase: A valid token verifies, a token with one flipped payload byte returns bad_signature, and an expired token returns expired.
Phase 5: Protected route middleware
Extract the bearer token, verify it, and attach the subject to the request or return 401 with the specific code. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.
import { verify } from './verify.js';
export function authenticate(req, { secret, issuer }) {
const header = req.headers.authorization ?? '';
const match = /^Bearer (.+)$/.exec(header);
if (!match) return { ok: false, status: 401, body: { error: 'missing_token' } };
const result = verify(match[1], secret, { issuer });
if (!result.ok) return { ok: false, status: 401, body: { error: result.code } };
return { ok: true, subject: result.claims.sub };
}
Acceptance for this phase: A request without a bearer header returns missing_token, a tampered token returns bad_signature, and a valid token yields the subject.
Phase 6: Server and tests
Wire a login endpoint and a protected endpoint, then cover signing, verification, and every failure code with tests. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.
import { createServer } from 'node:http';
import { sign } from './sign.js';
import { buildClaims } from './claims.js';
import { authenticate } from './middleware.js';
const SECRET = process.env.JWT_SECRET ?? 'dev-only-secret';
const ISSUER = 'jwt-service';
const server = createServer((req, res) => {
if (req.url === '/login' && req.method === 'POST') {
const claims = buildClaims('user-1', { issuer: ISSUER });
return send(res, 200, { token: sign(claims, SECRET) });
}
if (req.url === '/me') {
const auth = authenticate(req, { secret: SECRET, issuer: ISSUER });
return auth.ok ? send(res, 200, { sub: auth.subject }) : send(res, auth.status, auth.body);
}
send(res, 404, { error: 'not_found' });
});
function send(res, status, body) {
res.writeHead(status, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
}
server.listen(process.env.PORT ?? 3000);
export { server };
Acceptance for this phase: Login returns a token, calling /me with that token returns the subject, and calling /me without it returns 401 missing_token.
Testing strategy
Run npx vitest. Signing tests assert the token has three segments and that changing one byte of the payload invalidates it. Verification tests cover valid tokens, expired tokens, wrong-issuer tokens, and tokens signed with a different secret, each asserting a distinct error code. A timing test asserts the comparison uses the timing-safe function rather than string equality.
Distinct error codes are the point: an expired token should prompt a refresh, while a tampered token should prompt re-authentication, and the caller cannot tell them apart from a generic failure.
Extending the project
Role-based claims extend the claim set and add one check in middleware; refresh tokens are a second signed artefact with a longer expiry; and swapping HMAC for asymmetric signing replaces only the sign and verify primitives because the rest operates on the compact string.