Token Expiry
Part of the Auth and Security section of Coddy's Node.js journey. Lesson 12 of 17.
A server cannot take a token back: nothing is stored, so a stolen one works until it expires. Keep tokens short-lived, minutes rather than days, and let the client ask for a new one.
jwtVerify already refuses a token whose exp has passed. It throws errors.JWTExpired, so you can tell an expired token from a forged one and say so: a client that reads Token expired knows to log in again.
import { errors, jwtVerify } from 'jose';
try {
await jwtVerify(inviteToken, inviteKey);
} catch (err) {
if (err instanceof errors.JWTExpired) {
return res.status(410).json({ error: 'This invite has run out' });
}
return res.status(400).json({ error: 'Not a real invite' });
}Challenge
Easy- Tokens from
POST /tokenexpire after 15 minutes. - An expired token answers 401
{ "error": "Token expired" }. - Every other bad or missing token still answers 401
{ "error": "Log in first" }.
Get a token and read its exp with GET /inspect.
Try it yourself
import express from 'express';
import { SignJWT, decodeJwt, jwtVerify } from 'jose';
import { users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const app = express();
app.use(express.json());
app.post('/signup', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
const password = String(req.body.password ?? '');
if (!username || password.length < 8) {
return res.status(400).json({ error: 'Pick a username and a password of at least 8 characters' });
}
if (await users.findOne({ username })) {
return res.status(409).json({ error: 'That username is taken' });
}
await users.insertOne({ username, passwordHash: await hashPassword(password) });
res.status(201).json({ username });
});
app.post('/login', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
const user = await users.findOne({ username });
if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
return res.status(401).json({ error: 'Wrong username or password' });
}
res.json({ username: user.username });
});
app.post('/token', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
const user = await users.findOne({ username });
if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
return res.status(401).json({ error: 'Wrong username or password' });
}
const token = await new SignJWT({ username: user.username })
.setProtectedHeader({ alg: 'HS256' })
.setSubject(user._id.toHexString())
.setIssuedAt()
.setExpirationTime('1h')
.sign(secret);
res.json({ token });
});
// Checks the token in the Authorization header, or answers 401.
async function requireUser(req, res, next) {
const token = (req.get('authorization') ?? '').replace(/^Bearer /, '');
let payload;
try {
({ payload } = await jwtVerify(token, secret));
} catch {
return res.status(401).json({ error: 'Log in first' });
}
req.user = { id: payload.sub, username: payload.username };
next();
}
app.get('/me', requireUser, (req, res) => {
res.json(req.user);
});
// Shows what a token says: GET /inspect?token=...
app.get('/inspect', (req, res) => {
try {
res.json(decodeJwt(String(req.query.token ?? '')));
} catch {
res.status(400).json({ error: 'Not a JWT' });
}
});
// The admin page. No claim can be trusted before its signature is checked.
app.get('/admin', (req, res) => {
res.status(403).json({ error: 'Admins only' });
});
app.listen(3000, () => {
console.log('Vault is running on port 3000');
});
All lessons in Auth and Security
2Sessions and Cookies
Remembering with CookiesLogin Sessions