Authentication in a Node API

Intermediate · 30 min

Implement password login and JWT-protected routes in Express using scrypt and jsonwebtoken, with role guards, and know when sessions or Passport fit instead.

Before thisBuilding a REST API with ExpressHashing, HMAC and randomness with crypto

PedroTech · 183 min · from 1:03:38

Authentication in a Node API

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by PedroTechReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Authentication in an Express API is three pieces: store a salted slow hash of the password, verify it at login, and issue something (a signed JWT or a session id) that later requests present.
  • Hash passwords with a deliberately slow function. `crypto.scrypt` is built into Node, and bcrypt and argon2 are the usual packages. Compare derived keys with `crypto.timingSafeEqual`.
  • Return the same 401 whether the email was unknown or the password wrong, and do equivalent hashing work in both cases, so an attacker cannot tell which emails exist.
  • A JWT middleware reads `Authorization: Bearer`, calls `jwt.verify` with a pinned `algorithms` list, and sets `req.user`. Use short expiries; expired tokens throw `TokenExpiredError`.
  • 401 means 'not authenticated', 403 means 'authenticated but not allowed'. Express route-level guards like `requireRole('admin')` compose after `requireAuth`.

What this lesson covers, and what it does not

This is the Node implementation. The theory lives elsewhere, and it is worth reading first:

Here: how the pieces look in an Express app.

Storing and checking passwords

Node’s crypto module has scrypt, a memory-hard password hash, built in. The packages bcrypt and argon2 are the common alternatives, with the same shape: a salt, a slow computation, and a verify function.

import { scrypt, randomBytes, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';
const scryptP = promisify(scrypt);

async function hashPassword(password) {
  const salt = randomBytes(16);
  const key = await scryptP(password, salt, 64);
  return `${salt.toString('hex')}:${key.toString('hex')}`;
}

async function verifyPassword(password, stored) {
  const [saltHex, keyHex] = stored.split(':');
  const key = await scryptP(password, Buffer.from(saltHex, 'hex'), 64);
  return timingSafeEqual(key, Buffer.from(keyHex, 'hex'));
}

The salt is random per user and stored with the hash. timingSafeEqual compares in constant time, so response time does not leak how many bytes matched. The scrypt call runs on libuv’s thread pool, so it does not block the event loop the way a synchronous hash would. Details of the crypto APIs are in hashing, HMAC and randomness.

Login that does not leak

const DUMMY = await hashPassword('dummy-password'); // computed once at startup

app.post('/auth/login', async (req, res) => {
  const { email, password } = req.body ?? {};
  const user = users.get(email);
  const ok = await verifyPassword(String(password), user?.hash ?? DUMMY);
  if (!user || !ok) return res.status(401).json({ error: 'invalid credentials' });
  const token = jwt.sign({ role: user.role }, JWT_SECRET, {
    subject: String(user.id), expiresIn: '15m', algorithm: 'HS256',
  });
  res.json({ token });
});

An unknown email still pays for one scrypt call against DUMMY, and both failures return the same 401. In my test, a wrong password and an unknown email both returned 401. The token carries the user id as sub, the role, and iat/exp timestamps. Anyone can read the payload (it is base64url, not encrypted), so never put secrets in it. Load JWT_SECRET from configuration, with at least 32 random bytes.

Protecting routes

function requireAuth(req, res, next) {
  const [scheme, token] = (req.get('authorization') ?? '').split(' ');
  if (scheme !== 'Bearer' || !token) return res.status(401).json({ error: 'missing token' });
  try {
    const claims = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] });
    req.user = { id: Number(claims.sub), role: claims.role };
    next();
  } catch (err) {
    res.status(401).json({ error: err.name === 'TokenExpiredError' ? 'token expired' : 'invalid token' });
  }
}

const requireRole = (role) => (req, res, next) =>
  req.user.role === role ? next() : res.status(403).json({ error: 'forbidden' });

app.get('/me', requireAuth, (req, res) => res.json(req.user));
app.get('/admin', requireAuth, requireRole('admin'), (req, res) => res.json({ secret: 42 }));

These are plain middleware. I ran the whole app with jsonwebtoken 9 on Node 26:

  • no token: 401 missing token; valid token on /me: 200 {"id":1,"role":"admin"};
  • tampered token: 401 invalid token; expired token: 401 token expired;
  • an unsigned alg: none token claiming admin: 401, because algorithms is pinned;
  • a normal user on /admin: 403 forbidden.

401 means “I don’t know who you are”, 403 means “I know, and the answer is no”. For permission models beyond one role field, see authorization models.

JWTs, sessions and Passport

A JWT is stateless: the server needs no storage to verify it, which suits APIs and service-to-service calls. The price is revocation. A stolen token is valid until it expires, so keep access tokens short and pair them with refresh tokens you can revoke. For a browser app on your own domain, server-side sessions with an HttpOnly cookie are often simpler and safer than keeping a token in JavaScript, because you can end a session instantly. In Express that means express-session with a store such as Redis.

Passport is a middleware framework that standardises “strategies” (local password, Google, GitHub, JWT). It is useful when you support several login methods. For one password flow, the code above is shorter than the configuration. Whichever you choose, rate-limit the login route and add the security middleware from the REST lesson.

What the video covers

This lesson embeds a 30-minute clip, 1:03:38 to 1:33:38, of PedroTech’s December 2025 “Backend Complete Course”, the chapter titled “JWT Authentication”. I could not read a transcript, so I have not confirmed whether it uses bcrypt, how it stores the token, or whether it sets cookies. The clip belongs to a sponsored video and sits in a Prisma and PostgreSQL project, so it assumes a database that this page does not. The scrypt code, the timing-safe login, the pinned algorithm and the role guards are this page’s, run on Node 26. Web Dev Simplified’s 2019 JWT tutorial under “go deeper” covers access and refresh tokens with Express.

Where this fits

Authentication is the first thing that makes an API stateful about users, which connects to environment configuration for secrets and to securing dependencies for the libraries you rely on. Next in this group: other frameworks, starting with Fastify.

Check yourself

  1. 01Why must a login endpoint return the same error for 'no such user' and 'wrong password'?

    Different messages (or noticeably different response times) let an attacker test which emails have accounts. Return one generic 401, and when the user is not found still run a hash verification against a dummy hash so the timing matches.

  2. 02What attack does pinning `algorithms: ['HS256']` in `jwt.verify` prevent?

    Algorithm confusion. If the verifier trusts the token's own `alg` header, an attacker can set it to `none` or switch between asymmetric and symmetric algorithms. Pinning the allowed list rejects such tokens; in a test, an unsigned `alg: none` token got 401.

  3. 03When would you choose server-side sessions over JWTs for a Node app?

    When you need instant revocation (logout, ban, password change) or the client is a browser app on your own domain, where an HttpOnly cookie holding a session id is simpler and safer than storing a token in JavaScript. JWTs fit stateless APIs and service-to-service calls, but revoking one before expiry needs extra state.

  4. 04A user gets 403 on `/admin` but 200 on `/me`. What does that tell you?

    Authentication succeeded, because the token is valid and identifies the user, but authorization failed, since the role is not admin. A missing or invalid token would have produced 401 instead.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark