Menu
CoddyTech

Signing Tokens

Part of the Auth and Security section of Coddy's Node.js journey. Lesson 10 of 17.

A token is only worth something if nobody else can make one. jose signs it with HS256: an HMAC of the header and payload, keyed by a secret only the server knows.

The secret comes from an environment variable, process.env.JWT_SECRET, never from the code: code is shared, copied and committed. This lesson sets JWT_SECRET for you. jose wants it as bytes.

const key = new TextEncoder().encode(process.env.INVITE_SECRET);

const invite = await new SignJWT({ room: 'design' })
    .setProtectedHeader({ alg: 'HS256' })
    .setSubject(guestId)
    .setIssuedAt()
    .setExpirationTime('2d')
    .sign(key);

setSubject takes text, and setExpirationTime takes a span like '30m' or '2d'.

challenge icon

Challenge

Easy
  • POST /token with { username, password } answers { token }: HS256, signed with JWT_SECRET, claim username, subject the user's id as text, expiring in 1 hour.
  • A wrong login answers 401 { "error": "Wrong username or password" }.

Sign up, get a token, and paste it into GET /inspect?token=.

Try it yourself

import express from 'express';
import { decodeJwt } from 'jose';
import { users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';

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 });
});

// 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