JWT authentication
Overview
A JSON Web Token (JWT, pronounced “jot”) is a compact, signed statement such as “this is user 7, a learner, valid until 10:45”. The server issues it at login; the client sends it back with each request; the server checks the signature and trusts the contents — without looking anything up.
That makes JWTs popular for mobile apps, single-page apps calling APIs on other domains, and service-to-service authentication.
Anatomy of a JWT
- Header — the signing algorithm.
- Payload — the claims. Standard ones include
sub(subject — the user ID),iat(issued at),exp(expires),iss(issuer) andaud(audience). You can add your own, likerole. - Signature — computed from the header and payload with a secret key. If anyone changes a single character of the payload, the signature no longer matches.
The payload is not encrypted. Paste any JWT into a decoder and you can read it. Put IDs and roles in it — never passwords, personal data or anything secret.
Issuing tokens
npm install jsonwebtoken// src/auth/tokens.js
import jwt from 'jsonwebtoken';
import { config } from '../config.js';
export function signAccessToken(user) {
return jwt.sign(
{ role: user.role }, // custom claims
config.jwtSecret,
{
subject: String(user.id), // sub
expiresIn: '15m', // exp
issuer: 'academy-api', // iss
audience: 'academy-web', // aud
algorithm: 'HS256',
},
);
}app.post('/auth/login', validate({ body: loginSchema }), async (req, res) => {
const user = await authService.login(req.validated.body);
res.json({ accessToken: signAccessToken(user), tokenType: 'Bearer', expiresIn: 900 });
});The secret must be long and random — at least 32 bytes — and live in an environment variable:
node -e "console.log(require('node:crypto').randomBytes(48).toString('base64url'))"Anyone who has the secret can create tokens for any user, so guard it like a database password.
Verifying tokens
Clients send the token in the Authorization header:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs…// src/auth/require-auth.js
import jwt from 'jsonwebtoken';
import { config } from '../config.js';
import { HttpError } from '../errors.js';
export function requireAuth(req, res, next) {
const [scheme, token] = (req.get('Authorization') ?? '').split(' ');
if (scheme !== 'Bearer' || !token) throw new HttpError(401, 'Missing bearer token');
try {
const claims = jwt.verify(token, config.jwtSecret, {
algorithms: ['HS256'],
issuer: 'academy-api',
audience: 'academy-web',
});
req.user = { id: Number(claims.sub), role: claims.role };
next();
} catch (err) {
throw new HttpError(401, err.name === 'TokenExpiredError' ? 'Token expired' : 'Invalid token');
}
}Always pass an explicit algorithms list. Some historic JWT attacks tricked servers into accepting tokens signed with a different algorithm — or no algorithm at all.
The revocation problem
JWTs are valid until they expire, and the server doesn’t keep a list of them. So if a token is stolen, or a user logs out or is banned, the token still works until exp. That’s the main trade-off compared with sessions.
The standard solution: make access tokens short-lived, and pair them with a refresh token.
- The access token (JWT, ~15 minutes) is sent with every API request.
- The refresh token (a long random string, days to weeks) is used only to get new access tokens. It’s stored server-side (hashed, like a password), so you can revoke it.
- Each refresh rotates the refresh token: the old one is invalidated and a new one issued. If an old refresh token is ever used again, that’s a sign it was stolen — revoke the whole family.
app.post('/auth/refresh', async (req, res) => {
const presented = req.cookies?.refresh;
const record = presented && (await refreshTokensRepo.findValid(hashToken(presented)));
if (!record) throw new HttpError(401, 'Please log in again');
await refreshTokensRepo.revoke(record.id); // rotate
const user = await usersRepo.findById(record.userId);
const newRefresh = randomBytes(32).toString('base64url');
await refreshTokensRepo.insert({ userId: user.id, tokenHash: hashToken(newRefresh) });
res.cookie('refresh', newRefresh, { httpOnly: true, secure: true, sameSite: 'strict', path: '/auth' });
res.json({ accessToken: signAccessToken(user) });
});(hashToken can be a simple SHA-256 — refresh tokens are long and random, unlike passwords.)
Where should the client keep tokens?
- Mobile apps: the platform’s secure storage (Keychain, Keystore).
- Browser apps: keep the access token in memory (a JavaScript variable), and the refresh token in an
HttpOnly,Secure,SameSitecookie. AvoidlocalStoragefor tokens — any script injected into your page (XSS) can read it.
Authorisation
Authentication answers “who are you?”. Authorisation answers “are you allowed to do this?” — and it must be checked on every request:
export const requireRole = (...roles) => (req, res, next) => {
if (!roles.includes(req.user.role)) throw new HttpError(403, 'Not allowed');
next();
};
router.delete('/courses/:id', requireAuth, requireRole('admin'), deleteCourse);Role checks aren’t enough on their own. Most real authorisation bugs are about ownership: user 7 requesting /orders/1234, which belongs to user 9. Always scope queries to the current user:
const order = await ordersRepo.findOne({ id: req.params.id, userId: req.user.id });
if (!order) throw new HttpError(404, 'Order not found'); // 404 hides that it existsThis class of bug — broken object-level authorisation — tops the OWASP API Security list.
Don’t build it all yourself
For production, consider an identity provider (Auth0, Clerk, Cognito, Keycloak, Supabase Auth, Firebase Auth) or a well-maintained library. They handle social logins, multi-factor authentication, password resets, token rotation and key rotation — the parts most often got wrong. Your API then just verifies their tokens (usually RS256-signed, with public keys fetched from a JWKS URL), exactly as in this topic.
Summary: sign with a strong secret, verify with an explicit algorithm, keep access tokens short, rotate refresh tokens, and check ownership on every request.
Bearer-token middleware
Write requireAuth middleware that reads Authorization: Bearer <token>, verifies it with jwt.verify (HS256, your secret, issuer academy-api), and sets req.user = { id, role } from the sub and role claims. Respond 401 with a clear message when the header is missing, the token is invalid, or it has expired.
import jwt from 'jsonwebtoken';
import { config } from './config.js';
export function requireAuth(req, res, next) {
// your code here
}import jwt from 'jsonwebtoken';
import { config } from './config.js';
export function requireAuth(req, res, next) {
const header = req.get('Authorization') ?? '';
const [scheme, token] = header.split(' ');
if (scheme !== 'Bearer' || !token) {
return res.status(401).json({ error: { message: 'Missing bearer token' } });
}
try {
const claims = jwt.verify(token, config.jwtSecret, {
algorithms: ['HS256'],
issuer: 'academy-api',
});
req.user = { id: claims.sub, role: claims.role };
next();
} catch (err) {
const message = err.name === 'TokenExpiredError' ? 'Token expired' : 'Invalid token';
res.status(401).json({ error: { message } });
}
}Summary
- A JWT is a signed, base64url-encoded JSON payload: header.payload.signature.
- Anyone can read the payload — the signature only proves it wasn’t changed. Never put secrets in it.
- Verify with a fixed algorithm list, check expiry, issuer and audience, and use a long random secret.
- Send it as
Authorization: Bearer <token>; keep access tokens short-lived (minutes). - Use rotating refresh tokens, stored server-side, so logins last without long-lived access tokens.