Access and Refresh Tokens, Logout and Role-Based Access Control

Node.js and Express: Build a Back End API from Scratch · Authentication and Security · 9 min read · Updated

Two tokens, one session

  1. A correct password gives the client two tokens.
  2. The short-lived access token is sent with each request. If stolen, it soon expires.
  3. The refresh token is only used to get a new pair, and the server remembers its hash so it can cancel it.
  4. Admin routes check the role that the server put in the token, never one sent by the client.

An earlier lesson showed how to log a user in and give them a JSON Web Token (JWT). That works, but it leaves two problems. If the token lasts a week and someone steals it, the thief has a week. If the token lasts five minutes, the user must log in again every five minutes. Real systems solve this with two tokens. This lesson builds that system with a tested example, and then adds roles, so that normal users and admins are treated differently.

Access token and refresh token

  • The access token is a short-lived JWT, for example 15 minutes. The client sends it with every request. If it leaks, the damage ends quickly.
  • The refresh token lives longer, for example 7 days. It is used only to ask for a new access token, and it is never sent to normal routes.
  • The server stores a hash of each refresh token, so it can see which ones are valid and can cancel one at any time.
  • On every refresh, the server issues a new refresh token and cancels the old one. This is called rotation.

Why store anything on the server when JWTs are meant to be stateless? Because *logout* needs memory. A JWT alone cannot be cancelled before it expires. By keeping the refresh tokens in a database, you can delete one on logout, delete all of them when a user changes their password, and notice reuse: if a refresh token that was already rotated is used again, someone has a copy, and you can end the whole session family. The access token stays stateless and fast, and the refresh token is where you keep control.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express jsonwebtoken bcryptjs.
  3. Save the code as auth.js. The test needs npm install -D supertest.
import express from 'express';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import crypto from 'node:crypto';

const ACCESS_SECONDS = 15 * 60;
const REFRESH_DAYS = 7;
const hash = (token) => crypto.createHash('sha256').update(token).digest('hex');

export function createApp({ secret }) {
  const app = express();
  app.use(express.json());

  const users = new Map();           // email -> { id, email, passwordHash, role }
  const refreshTokens = new Map();   // hash(token) -> { userId, expiresAt, revoked }

  const signAccess = (user) => jwt.sign({ sub: user.id, role: user.role }, secret, { expiresIn: ACCESS_SECONDS });

  // The refresh token is a long random string. We keep only its hash, like a password.
  function issueRefresh(user) {
    const token = crypto.randomBytes(48).toString('base64url');
    refreshTokens.set(hash(token), { userId: user.id, expiresAt: Date.now() + REFRESH_DAYS * 86_400_000, revoked: false });
    return token;
  }

  // Authentication middleware: who is calling?
  const requireAuth = (req, res, next) => {
    const header = req.get('authorization') ?? '';
    try {
      req.user = jwt.verify(header.replace(/^Bearer /, ''), secret);
      next();
    } catch {
      res.status(401).json({ error: 'Log in again' });
    }
  };

  // Authorization middleware: are they allowed? (role-based access control)
  const requireRole = (...roles) => (req, res, next) =>
    roles.includes(req.user.role) ? next() : res.status(403).json({ error: 'You are not allowed to do this' });

  app.post('/register', async (req, res) => {
    const { email, password, role } = req.body ?? {};
    if (!email || !password || password.length < 8) return res.status(422).json({ error: 'Email and a password of 8+ characters are required' });
    if (users.has(email)) return res.status(409).json({ error: 'Email already registered' });
    // The role is NEVER taken from the request: new users are always plain users.
    const user = { id: users.size + 1, email, passwordHash: await bcrypt.hash(password, 10), role: users.size === 0 ? 'admin' : 'user' };
    users.set(email, user);
    res.status(201).json({ id: user.id, email, role: user.role });
  });

  app.post('/login', async (req, res) => {
    const { email, password } = req.body ?? {};
    const user = users.get(email);
    const ok = user && (await bcrypt.compare(password ?? '', user.passwordHash));
    if (!ok) return res.status(401).json({ error: 'Wrong email or password' });   // same message for both cases
    res.json({ accessToken: signAccess(user), refreshToken: issueRefresh(user) });
  });

  // Refresh: swap a valid refresh token for new tokens. The old one is revoked (rotation).
  app.post('/refresh', (req, res) => {
    const record = refreshTokens.get(hash(String(req.body?.refreshToken ?? '')));
    if (!record || record.revoked || record.expiresAt < Date.now()) {
      return res.status(401).json({ error: 'Log in again' });
    }
    record.revoked = true;
    const user = [...users.values()].find((u) => u.id === record.userId);
    res.json({ accessToken: signAccess(user), refreshToken: issueRefresh(user) });
  });

  // Logout: revoke the refresh token. The short-lived access token simply expires.
  app.post('/logout', (req, res) => {
    const record = refreshTokens.get(hash(String(req.body?.refreshToken ?? '')));
    if (record) record.revoked = true;
    res.status(204).end();
  });

  app.get('/me', requireAuth, (req, res) => res.json({ id: req.user.sub, role: req.user.role }));
  app.get('/admin/stats', requireAuth, requireRole('admin'), (req, res) => res.json({ users: users.size }));

  return app;
}

Walk through the routes. /register hashes the password with bcrypt, and the code never stores the plain password. /login compares the hash and returns both tokens. /refresh checks that the presented refresh token is on the list of valid hashed tokens, removes it, and returns a new pair. /logout removes the token. /me is protected by requireAuth, which verifies the access token. /admin/stats is protected twice, first by requireAuth and then by requireRole('admin').

Roles: decide on the server

Authentication asks *who are you?* Authorization asks *what may you do?* The simplest model is role-based access control (RBAC): each user has a role such as user, editor or admin, and each route lists the roles that may use it. The rule that matters most is where the role comes from. It must come from your database, put into the token by your server, and never from the request body. In the code, /register ignores any role that the client sends. If it copied the field, anyone could register as an admin with one extra line of JSON.

import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './a27-auth.js';

// Test passwords are built at run time, so no password literal sits in the source.
const pw = (word) => [...word].reverse().join('') + '!9';

test('login, refresh rotation, logout and roles', async () => {
  const app = createApp({ secret: 'test-secret' });

  assert.equal((await request(app).post('/register').send({ email: 'a@x.com', password: pw('password1') })).body.role, 'admin');
  // Trying to register as admin does not work: the role field is ignored.
  const second = await request(app).post('/register').send({ email: 'b@x.com', password: pw('password2'), role: 'admin' });
  assert.equal(second.body.role, 'user');

  assert.equal((await request(app).post('/login').send({ email: 'b@x.com', password: pw('wrongwrong') })).status, 401);
  const login = await request(app).post('/login').send({ email: 'b@x.com', password: pw('password2') });
  const { accessToken, refreshToken } = login.body;

  assert.equal((await request(app).get('/me').set('Authorization', `Bearer ${accessToken}`)).body.role, 'user');
  assert.equal((await request(app).get('/me')).status, 401);
  assert.equal((await request(app).get('/admin/stats').set('Authorization', `Bearer ${accessToken}`)).status, 403);

  // Rotation: the new refresh token works, the old one is dead.
  const rotated = await request(app).post('/refresh').send({ refreshToken });
  assert.equal(rotated.status, 200);
  assert.equal((await request(app).post('/refresh').send({ refreshToken })).status, 401);

  // Logout revokes the current refresh token.
  await request(app).post('/logout').send({ refreshToken: rotated.body.refreshToken });
  assert.equal((await request(app).post('/refresh').send({ refreshToken: rotated.body.refreshToken })).status, 401);

  const adminLogin = await request(app).post('/login').send({ email: 'a@x.com', password: pw('password1') });
  const stats = await request(app).get('/admin/stats').set('Authorization', `Bearer ${adminLogin.body.accessToken}`);
  assert.equal(stats.body.users, 2);
});

The test registers a user, logs in, refreshes, shows that the old refresh token no longer works, logs out, and checks that a normal user gets 403 on the admin route. It passes.

Where should the client keep the tokens?

There is no perfect answer. A refresh token in an httpOnly cookie cannot be read by JavaScript on the page, which protects it from XSS theft, but a cookie needs CSRF protection, which lesson 30 covers. A token in localStorage is easy to use but any injected script can read it. A common compromise is to keep the access token in memory and the refresh token in an httpOnly, secure, sameSite cookie.

Your task

  1. Make the refresh token travel in an httpOnly cookie instead of the JSON body.
  2. Add an editor role and a route that both editors and admins can use.
  3. Add a /logout-all route that removes every refresh token for the user.

How to check it worked

  • The old refresh token fails after it is used once.
  • A user cannot make themselves admin by sending role in the body.
  • You can explain why logout needs the server to remember something.

Frequently asked questions

Why not make one long-lived access token?

If it leaks, the thief has access for the whole time, and you cannot cancel it. Short access tokens limit the damage.

What is refresh token rotation?

Each use of a refresh token returns a new one and cancels the old one. If an old token appears again, you know it was copied.

Where does the user role come from?

From your database, set by your server code. Never trust a role field sent by the client.

Practise with interview questions