TExcelTAD
Home › Express & NestJS › Authentication Basics

Authentication Basics

Authentication answers "who is making this request?". HTTP is stateless — every request stands alone — so the client must prove its identity on every request. There are two classic ways to do that: sessions and tokens.

Sessions vs tokens

Server-side session Signed token (e.g. JWT)
What the client holds a random session id in a cookie a token containing the user id + signature
Where user data lives server store (memory, Redis, DB) inside the token itself
Logout / revoke delete the session — instant hard: token stays valid until it expires
Scaling to many servers needs a shared store any server with the secret can verify
Typical clients browser apps on the same site mobile apps, SPAs, service-to-service
Sent as Cookie: header (automatic) Authorization: Bearer <token>

Neither is "better". Cookie sessions are simpler and safer for classic web apps; tokens shine for APIs consumed by many kinds of clients.

Step 1: never store plain passwords

Store a slow, salted hash instead. Node's built-in crypto.scrypt is designed for this. The salt is random per user in real life; it's fixed here to keep the output reproducible:

node · try it yourself
const crypto = require('node:crypto');

function hashPassword(password, salt) {
  const hash = crypto.scryptSync(password, salt, 32);
  return `${salt}:${hash.toString('hex')}`;
}

function verifyPassword(password, stored) {
  const [salt, hashHex] = stored.split(':');
  const expected = Buffer.from(hashHex, 'hex');
  const actual = crypto.scryptSync(password, salt, 32);
  return crypto.timingSafeEqual(expected, actual); // constant-time comparison
}

const stored = hashPassword('correct horse', 'demo-salt'); // real code: a random 16-byte salt per user
console.log('stored length:', stored.length);
console.log('right password:', verifyPassword('correct horse', stored));
console.log('wrong password:', verifyPassword('Correct horse', stored));
stored length: 74
right password: true
wrong password: false

Note: timingSafeEqual takes the same time whether the first or the last byte differs, so attackers can't guess a secret byte by byte from response times. Never compare secrets with ===.

Step 2: a signed token

A token is useful only if the client can't forge it. An HMAC signature over the payload, computed with a server secret, makes any tampering detectable. This is the same idea JWTs use (HS256), stripped to the essentials:

node · try it yourself
const crypto = require('node:crypto');

const SECRET = 'change-me-in-production';
const b64 = (s) => Buffer.from(s).toString('base64url');
const sign = (data) => crypto.createHmac('sha256', SECRET).update(data).digest('base64url');

function createToken(payload) {
  const body = b64(JSON.stringify(payload));
  return `${body}.${sign(body)}`;
}

function readToken(token, now) {
  const [body, sig] = String(token).split('.');
  if (!body || !sig) return null;
  const expected = Buffer.from(sign(body));
  const given = Buffer.from(sig);
  if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) return null;
  const payload = JSON.parse(Buffer.from(body, 'base64url').toString());
  if (payload.exp <= now) return null; // expired
  return payload;
}

const NOW = 1_700_000_000; // fixed "current time" in seconds, for a reproducible demo
const token = createToken({ sub: 'user-1', role: 'editor', exp: NOW + 3600 });
console.log('token:', token);
console.log('valid:', readToken(token, NOW));

const [body, sig] = token.split('.');
const forgedBody = b64(JSON.stringify({ sub: 'user-1', role: 'admin', exp: NOW + 3600 }));
console.log('forged:', readToken(`${forgedBody}.${sig}`, NOW));
console.log('expired:', readToken(token, NOW + 7200));
token: eyJzdWIiOiJ1c2VyLTEiLCJyb2xlIjoiZWRpdG9yIiwiZXhwIjoxNzAwMDAzNjAwfQ.WVC8DPd43whjJcfO6lWmE00r2tfZh1w6SH5U3yI1OTs
valid: { sub: 'user-1', role: 'editor', exp: 1700003600 }
forged: null
expired: null

The payload is only encoded, not encrypted — anyone can read it. Never put secrets in a token. The signature just guarantees nobody changed it.

Step 3: login and a protected route

Put the pieces together: POST /login checks the password and returns a token; an authenticate middleware verifies the Authorization: Bearer … header and sets req.user:

node · try it yourself
const express = require('express');
const crypto = require('node:crypto');

const SECRET = 'change-me-in-production';
const NOW = () => 1_700_000_000; // real code: the current Unix time in seconds
const sign = (d) => crypto.createHmac('sha256', SECRET).update(d).digest('base64url');
const createToken = (p) => { const b = Buffer.from(JSON.stringify(p)).toString('base64url'); return `${b}.${sign(b)}`; };
function readToken(token) {
  const [b, s] = String(token).split('.');
  if (!b || !s) return null;
  const ok = Buffer.from(sign(b)), given = Buffer.from(s);
  if (ok.length !== given.length || !crypto.timingSafeEqual(ok, given)) return null;
  const payload = JSON.parse(Buffer.from(b, 'base64url').toString());
  return payload.exp > NOW() ? payload : null;
}
const hash = (pw) => crypto.scryptSync(pw, 'demo-salt', 32).toString('hex');

const users = [{ id: 'u1', email: 'ana@example.com', passwordHash: hash('s3cret!') }];

function authenticate(req, res, next) {
  const [scheme, token] = (req.get('Authorization') ?? '').split(' ');
  const payload = scheme === 'Bearer' ? readToken(token) : null;
  if (!payload) return res.status(401).set('WWW-Authenticate', 'Bearer').json({ error: 'Not authenticated' });
  req.user = { id: payload.sub };
  next();
}

const app = express();
app.use(express.json());

app.post('/login', (req, res) => {
  const user = users.find((u) => u.email === req.body?.email);
  // same message for "unknown email" and "wrong password": don't reveal which accounts exist
  if (!user || !crypto.timingSafeEqual(Buffer.from(user.passwordHash), Buffer.from(hash(String(req.body?.password))))) {
    return res.status(401).json({ error: 'Invalid email or password' });
  }
  res.json({ token: createToken({ sub: user.id, exp: NOW() + 900 }) });
});

app.get('/me', authenticate, (req, res) => res.json({ userId: req.user.id }));

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const login = (email, password) => fetch(base + '/login', {
    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }),
  });

  let res = await login('ana@example.com', 'wrong');
  console.log('bad login :', res.status, await res.text());
  res = await login('ana@example.com', 's3cret!');
  const { token } = await res.json();
  console.log('good login:', res.status, 'token received');

  res = await fetch(base + '/me');
  console.log('no token  :', res.status, res.headers.get('www-authenticate'), await res.text());
  res = await fetch(base + '/me', { headers: { Authorization: `Bearer ${token}` } });
  console.log('with token:', res.status, await res.text());
  server.close();
});
bad login : 401 {"error":"Invalid email or password"}
good login: 200 token received
no token  : 401 Bearer {"error":"Not authenticated"}
with token: 200 {"userId":"u1"}

In real projects

Task Use
JWT creation/verification jose or jsonwebtoken
cookie sessions express-session with a Redis/DB store
password hashing crypto.scrypt, argon2 or bcrypt
"Log in with Google/GitHub" OAuth 2 / OpenID Connect (openid-client, Passport strategies)

Tip: When you put a token in a cookie, set httpOnly (JavaScript can't steal it), secure (HTTPS only) and sameSite: 'lax' (mitigates CSRF).

Test yourself

What does the HMAC signature on a token guarantee?

  1. The payload is encrypted
  2. The payload was not modified by someone without the secret
  3. The token never expires
  4. The user is an admin

Why is logout harder with stateless tokens than with sessions?

  1. Tokens can't be deleted from the client
  2. A valid token stays usable until it expires unless you keep a revocation list
  3. Tokens are stored in the database
  4. Sessions don't support logout either

Why should login reply with the same error for an unknown email and a wrong password?

  1. It's shorter
  2. To avoid revealing which email addresses have accounts
  3. HTTP requires it
  4. To make tests easier