Polski

Tutorial · Authentication · Express

Backend login and registration – passwords, sessions, JWT, refresh token rotation and OAuth

We build authentication for the pierogi shop API in Express 5 (plus a NestJS variant) – argon2id password hashing, short-lived JWTs and rotated refresh tokens in httpOnly cookies with reuse detection, e-mail verification, password reset, rate limits and lockouts, Google sign-in (OIDC + PKCE) and a checklist based on OWASP ASVS 5.0.

By · · 37 min read

A login form looks innocent: two fields and a button. Behind it, though, hide a dozen decisions, each of which can end in a breach – from how passwords are stored, through where tokens live, to a "no such user" message. In this tutorial you build authentication for the customers of Halina's pierogi shop from scratch, with code you can test and a reason for every decision.

Prerequisites: REST API with Express 5 (project layout, error handling), HTTP basics: headers, cookies, CORS. For the NestJS variant – NestJS in practice.

19 MiB
of memory per hash – argon2id as recommended by OWASP
15 min
access token lifetime – a stateless JWT
30 days
refresh token lifetime – rotated on every use
15
characters minimum – NIST 800-63B-4 for password-only login

Sessions or JWT?

This is the first question and the source of many misunderstandings. Both approaches work; they differ in where the state lives.

Server-side sessionJWT onlyHybrid (this tutorial)
What the client holdsa random session id in a cookiea signed token with dataa short JWT + a refresh token in a cookie
Checking a requestread from Redis/databasesignature check, no I/Osignature check, no I/O
Logout, account lockimmediateonly after the token expireswithin 15 min (refresh immediately)
Scaling, many servicesa shared session storeevery service verifies itselfevery service verifies itself
Whenclassic web app, one backendservice-to-service callsSPA/mobile + API, several services

Server-side sessions (e.g. express-session with the connect-redis store) are still a great choice for a server-rendered app. The hybrid combines the best of both: most requests are verified without a database query, and the long-lived piece (the refresh token) sits in the database and can be revoked instantly.

Diagram: Login, refresh with rotation and detecting a stolen refresh token

Step 1. The project and configuration

npm install express zod cookie-parser cors helmet express-rate-limit jose @node-rs/argon2 arctic
npm install -D typescript tsx vitest supertest @types/node @types/express @types/cookie-parser @types/cors @types/supertest

Project configuration

package.json
{
  "name": "pierogi-auth",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": {
    "node": ">=22.12"
  },
  "scripts": {
    "dev": "tsx watch --env-file-if-exists=.env src/server.ts",
    "build": "tsc -p tsconfig.build.json",
    "start": "node --env-file-if-exists=.env dist/server.js",
    "typecheck": "tsc --noEmit",
    "test": "vitest run"
  },
  "dependencies": {
    "@node-rs/argon2": "^2.2.2",
    "arctic": "^3.7.0",
    "cookie-parser": "^1.4.7",
    "cors": "^2.8.6",
    "express": "^5.3.0",
    "express-rate-limit": "^8.7.5",
    "helmet": "^8.3.0",
    "jose": "^6.2.18",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/cookie-parser": "^1.4.10",
    "@types/cors": "^2.8.19",
    "@types/express": "^5.0.6",
    "@types/node": "^24.19.4",
    "@types/supertest": "^7.2.1",
    "supertest": "^7.3.2",
    "tsx": "^4.23.15",
    "typescript": "^7.0.2",
    "vitest": "^5.1.2"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "nodenext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "noEmit": true,
    "types": ["node"]
  },
  "include": ["src", "test"]
}
tsconfig.build.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": { "noEmit": false, "rootDir": "src", "outDir": "dist" },
  "include": ["src"]
}
.env.example
NODE_ENV=development
PORT=3000
APP_URL=http://localhost:5173
API_URL=http://localhost:3000
CORS_ORIGINS=http://localhost:5173
# openssl rand -base64 48
JWT_SECRET=replace-with-at-least-32-random-characters
ACCESS_TOKEN_TTL_SEC=900
REFRESH_TOKEN_TTL_DAYS=30
# Optional: Google sign-in (console.cloud.google.com -> Credentials -> OAuth client ID)
# Authorized redirect URI: http://localhost:3000/auth/google/callback
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
src/config.ts
import { z } from 'zod';

const EnvSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  // Front-end URL used in e-mail links and OAuth redirects back to the app.
  APP_URL: z.url().default('http://localhost:5173'),
  API_URL: z.url().default('http://localhost:3000'),
  CORS_ORIGINS: z
    .string()
    .default('http://localhost:5173')
    .transform((v) => v.split(',').map((s) => s.trim())),
  // openssl rand -base64 48 – at least 256 bits for HS256.
  JWT_SECRET: z.string().min(32),
  JWT_ISSUER: z.string().default('pierogi-api'),
  JWT_AUDIENCE: z.string().default('pierogi-web'),
  ACCESS_TOKEN_TTL_SEC: z.coerce.number().int().positive().default(900),
  REFRESH_TOKEN_TTL_DAYS: z.coerce.number().int().positive().default(30),
  GOOGLE_CLIENT_ID: z.string().optional(),
  GOOGLE_CLIENT_SECRET: z.string().optional(),
});

export type Config = z.infer<typeof EnvSchema>;

export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
  const parsed = EnvSchema.safeParse(env);
  if (!parsed.success) {
    console.error(`Invalid environment configuration:\n${z.prettifyError(parsed.error)}`);
    process.exit(1);
  }
  return parsed.data;
}

JWT_SECRET must be at least 32 characters (256 bits for HS256) and come from a secrets manager. The short access token lifetime and the long refresh token lifetime are parameters, not constants – in a banking app you would shorten both.

Step 2. Passwords: argon2id and a sensible policy

Hashing, policy and breach checking

src/auth/password.ts
import { createHash } from 'node:crypto';
import { hash, parseOptions, verify } from '@node-rs/argon2';
import { z } from 'zod';

// OWASP Password Storage Cheat Sheet: argon2id, 19 MiB of memory, 2 iterations, 1 lane.
const ARGON2 = { memoryCost: 19_456, timeCost: 2, parallelism: 1 };

// NIST SP 800-63B-4: at least 15 characters for password-only login, no composition rules,
// allow long passphrases. The upper bound only protects the server from huge inputs.
export const PasswordSchema = z.string().min(15, 'Use at least 15 characters – a passphrase works best').max(128);

export function hashPassword(plain: string): Promise<string> {
  return hash(plain, ARGON2); // the salt is generated and stored inside the PHC string
}

export function verifyPassword(stored: string, plain: string): Promise<boolean> {
  return verify(stored, plain);
}

// True when the hash was created with weaker parameters than today's – rehash after login.
export function needsRehash(stored: string): boolean {
  const current = parseOptions(stored);
  return current.memoryCost < ARGON2.memoryCost || current.timeCost < ARGON2.timeCost;
}

// Verified against for unknown e-mails, so they take as long as a wrong password.
export const DUMMY_HASH = await hashPassword('timing-equalizer-not-a-real-password');

// Have I Been Pwned "range" API with k-anonymity: only 5 hex chars of the SHA-1 leave the server.
export async function isBreachedPassword(plain: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {
  const sha1 = createHash('sha1').update(plain).digest('hex').toUpperCase();
  const prefix = sha1.slice(0, 5);
  const suffix = sha1.slice(5);
  try {
    const res = await fetchImpl(`https://api.pwnedpasswords.com/range/${prefix}`, {
      headers: { 'Add-Padding': 'true' },
      signal: AbortSignal.timeout(2_000),
    });
    if (!res.ok) return false;
    const body = await res.text();
    return body.split('\n').some((line) => {
      const [hashSuffix, count] = line.trim().split(':');
      return hashSuffix === suffix && Number(count) > 0; // padding rows have count 0
    });
  } catch {
    return false; // fail open: an outage of the API must not block sign-ups
  }
}

Choosing the algorithm. Passwords are hashed with deliberately slow, memory-hungry functions so that guessing on GPUs is expensive. SHA-256 – even salted – is unfit for this: it is designed to be fast.

AlgorithmStatusNotes
argon2idfirst choice (OWASP)m=19 MiB, t=2, p=1; resistant to GPUs and side-channel attacks
scryptgoodbuilt into Node.js (crypto.scrypt) – a zero-dependency option
bcryptacceptable in legacy systemscost ≥ 10; truncates the password to 72 bytes – long passphrases lose their point
PBKDF2when FIPS requires it600,000 iterations for HMAC-SHA-256
MD5, SHA-1, SHA-256never for passwordsbillions of guesses per second on one card

@node-rs/argon2 ships prebuilt binaries (no native compilation at install time), and its default parameters are exactly the OWASP recommendation – the code states them explicitly so that a library change cannot alter them. The hash uses the PHC format ($argon2id$v=19$m=19456,t=2,p=1$salt$hash), so the parameters and the salt are stored with it. needsRehash() lets you raise the parameters later: the password is rehashed on the next successful login.

Password policy according to NIST SP 800-63B-4 (2025):

  • at least 15 characters when the password is the only factor (8 if it is part of MFA), allow at least 64 characters;
  • no composition rules ("uppercase, digit, special character") and no periodic changes – force a change only when a compromise is suspected;
  • check the password against a list of compromised passwords when it is set or changed.

isBreachedPassword() uses the Have I Been Pwned API with k-anonymity: you send only the first 5 characters of the SHA-1 hash and match the rest locally – the service never learns which password you checked. The Add-Padding header adds fake rows so that even the response size reveals nothing.

Step 3. Tokens: access JWTs and opaque refresh tokens

Token service

src/auth/tokens.ts
import { createHash, randomBytes } from 'node:crypto';
import { errors, jwtVerify, SignJWT } from 'jose';
import type { Role } from './auth.store.js';

export interface AccessClaims {
  sub: string;
  role: Role;
}

export interface TokenConfig {
  secret: string;
  issuer: string;
  audience: string;
  accessTtlSec: number;
}

// Short-lived, stateless access token (JWT). Revocation = wait up to accessTtlSec.
export class TokenService {
  private readonly key: Uint8Array;

  constructor(private readonly cfg: TokenConfig) {
    this.key = new TextEncoder().encode(cfg.secret);
  }

  get accessTtlSec(): number {
    return this.cfg.accessTtlSec;
  }

  signAccess(user: { id: string; role: Role }): Promise<string> {
    return new SignJWT({ role: user.role })
      .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
      .setSubject(user.id)
      .setIssuer(this.cfg.issuer)
      .setAudience(this.cfg.audience)
      .setIssuedAt()
      .setExpirationTime(`${this.cfg.accessTtlSec}s`)
      .sign(this.key);
  }

  async verifyAccess(token: string): Promise<AccessClaims> {
    // Pin the algorithm, issuer and audience – never trust the token's own header.
    const { payload } = await jwtVerify(token, this.key, {
      algorithms: ['HS256'],
      issuer: this.cfg.issuer,
      audience: this.cfg.audience,
    });
    if (typeof payload.sub !== 'string' || (payload.role !== 'customer' && payload.role !== 'staff')) {
      throw new errors.JWTClaimValidationFailed('unexpected claims', payload);
    }
    return { sub: payload.sub, role: payload.role };
  }
}

export const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');

// Opaque random tokens (refresh, e-mail links): the client gets `token`, the database only `hash`.
export function newOpaqueToken(): { token: string; hash: string } {
  const token = randomBytes(32).toString('base64url');
  return { token, hash: sha256(token) };
}
  • The access token is a JWT signed with HS256 containing sub (the user id), role, iss, aud and exp. Verification pins the algorithm, issuer and audience – you do not trust the token's header (the classic attacks are alg: none or swapping RS256 for HS256).
  • Refresh tokens and e-mail links are 32 random bytes (base64url). The client gets the token, the database only its SHA-256. A leaked database copy does not let anyone take over a session. Plain SHA-256 is enough because the token has 256 bits of entropy – unlike passwords, it cannot be guessed.
  • HS256 or RS256/EdDSA? A symmetric key is simple when the same service issues and checks tokens. When several services verify them, use an asymmetric key and publish the public keys (JWKS) – services get only the public key and cannot forge tokens.

Step 4. Storage, lockouts and mail

Data model, attempt throttling and the mail port

src/auth/auth.store.ts
export type Role = 'customer' | 'staff';

export interface User {
  id: string;
  email: string; // normalized: trimmed, lower-case
  passwordHash: string | null; // null for accounts created with Google
  googleSub: string | null;
  role: Role;
  emailVerifiedAt: Date | null;
  createdAt: Date;
}

export interface RefreshToken {
  id: string;
  userId: string;
  familyId: string; // all tokens rotated from one login
  tokenHash: string;
  expiresAt: Date;
  revokedAt: Date | null;
  replacedById: string | null;
  userAgent?: string;
}

export type OneTimePurpose = 'verify-email' | 'reset-password';

export interface OneTimeToken {
  tokenHash: string;
  userId: string;
  purpose: OneTimePurpose;
  expiresAt: Date;
  usedAt: Date | null;
}

// In SQL: users(email UNIQUE), refresh_tokens(token_hash UNIQUE, family_id INDEX), one_time_tokens(token_hash UNIQUE).
export interface AuthStore {
  findUserByEmail(email: string): Promise<User | undefined>;
  findUserById(id: string): Promise<User | undefined>;
  findUserByGoogleSub(sub: string): Promise<User | undefined>;
  saveUser(user: User): Promise<void>;
  saveRefreshToken(token: RefreshToken): Promise<void>;
  findRefreshTokenByHash(hash: string): Promise<RefreshToken | undefined>;
  revokeRefreshFamily(familyId: string, at: Date): Promise<void>;
  revokeAllRefreshTokens(userId: string, at: Date): Promise<void>;
  saveOneTimeToken(token: OneTimeToken): Promise<void>;
  findOneTimeToken(hash: string, purpose: OneTimePurpose): Promise<OneTimeToken | undefined>;
}

export class InMemoryAuthStore implements AuthStore {
  private readonly users = new Map<string, User>();
  private readonly refreshTokens = new Map<string, RefreshToken>();
  private readonly oneTimeTokens = new Map<string, OneTimeToken>();

  async findUserByEmail(email: string) {
    return [...this.users.values()].find((u) => u.email === email);
  }
  async findUserById(id: string) {
    return this.users.get(id);
  }
  async findUserByGoogleSub(sub: string) {
    return [...this.users.values()].find((u) => u.googleSub === sub);
  }
  async saveUser(user: User) {
    this.users.set(user.id, { ...user });
  }
  async saveRefreshToken(token: RefreshToken) {
    this.refreshTokens.set(token.id, { ...token });
  }
  async findRefreshTokenByHash(hash: string) {
    const token = [...this.refreshTokens.values()].find((t) => t.tokenHash === hash);
    return token && { ...token };
  }
  async revokeRefreshFamily(familyId: string, at: Date) {
    for (const t of this.refreshTokens.values()) if (t.familyId === familyId) t.revokedAt ??= at;
  }
  async revokeAllRefreshTokens(userId: string, at: Date) {
    for (const t of this.refreshTokens.values()) if (t.userId === userId) t.revokedAt ??= at;
  }
  async saveOneTimeToken(token: OneTimeToken) {
    this.oneTimeTokens.set(token.tokenHash, { ...token });
  }
  async findOneTimeToken(hash: string, purpose: OneTimePurpose) {
    const token = this.oneTimeTokens.get(hash);
    return token?.purpose === purpose ? { ...token } : undefined;
  }
}
src/auth/login-throttle.ts
// Per-account throttling with exponential backoff, keyed by the normalized e-mail –
// it behaves the same for existing and non-existing accounts (no user enumeration).
// Single process only: with several instances keep the counters in Redis.
export class LoginThrottle {
  private readonly failures = new Map<string, { count: number; lockedUntil: number }>();

  constructor(
    private readonly freeAttempts = 5,
    private readonly maxLockMs = 15 * 60_000,
    private readonly now: () => number = Date.now,
  ) {}

  retryAfterMs(key: string): number {
    const entry = this.failures.get(key);
    return entry ? Math.max(0, entry.lockedUntil - this.now()) : 0;
  }

  registerFailure(key: string): void {
    const entry = this.failures.get(key) ?? { count: 0, lockedUntil: 0 };
    entry.count += 1;
    if (entry.count >= this.freeAttempts) {
      // 30 s, 60 s, 120 s ... up to 15 minutes – a temporary lock, never a permanent one.
      const lockMs = Math.min(this.maxLockMs, 30_000 * 2 ** (entry.count - this.freeAttempts));
      entry.lockedUntil = this.now() + lockMs;
    }
    this.failures.set(key, entry);
  }

  reset(key: string): void {
    this.failures.delete(key);
  }
}
src/auth/mailer.ts
export interface MailMessage {
  to: string;
  subject: string;
  text: string;
}

// Port: swap ConsoleMailer for an SES/SMTP adapter in production.
export interface Mailer {
  send(message: MailMessage): Promise<void>;
}

export class ConsoleMailer implements Mailer {
  async send({ to, subject, text }: MailMessage): Promise<void> {
    console.info(`[mail] to=${to} subject="${subject}"\n${text}\n`);
  }
}

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 5. The service: registration, verification, login, rotation, reset
  • Step 6. HTTP: cookies, middleware and routes
  • Step 7. Signing in with Google and GitHub (OAuth 2.0 and OpenID Connect)
  • Step 8. Testing attack scenarios
  • The NestJS variant: a global JWT guard
  • Checklist based on OWASP ASVS 5.0
  • Common mistakes
  • Check yourself
  • What's next

Create a free account · Sign in