English

Poradnik · Logowanie i rejestracja · Express

Logowanie i rejestracja na backendzie – hasła, sesje, JWT, rotacja refresh tokenów i OAuth

Budujemy uwierzytelnianie dla API pierogarni w Express 5 (i wariant w NestJS) – haszowanie haseł argon2id, krótkie tokeny JWT i rotowane refresh tokeny w ciasteczkach httpOnly z wykrywaniem ponownego użycia, weryfikacja e-maila, reset hasła, limity i blokady, logowanie przez Google (OIDC + PKCE) oraz lista kontrolna według OWASP ASVS 5.0.

Autor · · 35 min czytania

Formularz logowania wygląda niewinnie: dwa pola i przycisk. Za nim kryje się jednak kilkanaście decyzji, z których każda może skończyć się wyciekiem – od sposobu przechowywania haseł, przez miejsce trzymania tokenów, po komunikat „nie ma takiego użytkownika”. W tym poradniku budujesz uwierzytelnianie dla klientów pierogarni Haliny od zera, z kodem, który da się przetestować, i z uzasadnieniem każdej decyzji.

Wymagania wstępne: REST API w Express 5 (struktura projektu, obsługa błędów), podstawy HTTP: nagłówki, ciasteczka, CORS. Dla wariantu NestJS – NestJS w praktyce.

19 MiB
pamięci na jedno haszowanie – argon2id według OWASP
15 min
życia access tokena – JWT bez stanu
30 dni
życia refresh tokena – rotowany przy każdym użyciu
15
znaków minimum – NIST 800-63B-4 dla logowania samym hasłem

Sesje czy JWT?

To pierwsze pytanie i źródło wielu nieporozumień. Oba podejścia działają; różnią się tym, gdzie żyje stan.

Sesja po stronie serweraSam JWTHybryda (ten poradnik)
Co ma klientlosowy identyfikator sesji w ciasteczkupodpisany token z danymikrótki JWT + refresh token w ciasteczku
Sprawdzenie żądaniaodczyt z Redisa/bazyweryfikacja podpisu, bez I/Oweryfikacja podpisu, bez I/O
Wylogowanie, blokada kontanatychmiastdopiero po wygaśnięciu tokenapo maks. 15 min (refresh od razu)
Skalowanie, wiele serwisówwspólny magazyn sesjikażdy serwis sam weryfikujekażdy serwis sam weryfikuje
Kiedyklasyczna aplikacja webowa, jeden backendkomunikacja serwis–serwisSPA/mobile + API, kilka serwisów

Sesje po stronie serwera (np. express-session z magazynem connect-redis) to wciąż świetny wybór dla aplikacji renderowanej po stronie serwera. Hybryda łączy zalety obu: większość żądań weryfikuje się bez zapytania do bazy, a długowieczny element (refresh token) jest w bazie i da się go natychmiast unieważnić.

Diagram: Logowanie, odświeżanie z rotacją i wykrycie kradzieży refresh tokena

Krok 1. Projekt i konfiguracja

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

Konfiguracja projektu

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 musi mieć co najmniej 32 znaki (256 bitów dla HS256) i pochodzić z menedżera sekretów. Krótki czas życia access tokena i długi refresh tokena to parametry, nie stałe – w aplikacji bankowej skrócisz oba.

Krok 2. Hasła: argon2id i rozsądna polityka

Haszowanie, polityka i sprawdzanie wycieków

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

Wybór algorytmu. Hasła haszuje się funkcjami celowo wolnymi i pamięciożernymi, żeby zgadywanie na kartach graficznych było drogie. SHA-256 – nawet z solą – się do tego nie nadaje: jest zaprojektowany, by być szybki.

AlgorytmStatusUwagi
argon2idpierwszy wybór (OWASP)m=19 MiB, t=2, p=1; odporny na GPU i ataki bocznym kanałem
scryptdobrywbudowany w Node.js (crypto.scrypt) – opcja bez zależności
bcryptakceptowalny w starszych systemachkoszt ≥ 10; ucina hasło do 72 bajtów – długie frazy tracą sens
PBKDF2gdy wymaga tego FIPS600 000 iteracji dla HMAC-SHA-256
MD5, SHA-1, SHA-256nigdy dla hasełmiliardy prób na sekundę na jednej karcie

@node-rs/argon2 dostarcza gotowe binaria (bez kompilacji natywnej przy instalacji), a jego domyślne parametry to dokładnie zalecenie OWASP – w kodzie zapisujemy je jawnie, żeby zmiana biblioteki ich nie zmieniła. Skrót ma format PHC ($argon2id$v=19$m=19456,t=2,p=1$sól$skrót), więc parametry i sól są zapisane razem z nim. needsRehash() pozwala podnieść parametry w przyszłości: przy najbliższym udanym logowaniu hasło zostanie zahaszowane ponownie.

Polityka haseł według NIST SP 800-63B-4 (2025):

  • minimum 15 znaków, gdy hasło jest jedynym czynnikiem (8, jeśli jest częścią MFA), pozwól na co najmniej 64 znaki;
  • żadnych reguł złożoności („wielka litera, cyfra, znak specjalny”) i żadnej okresowej zmiany – wymuszaj zmianę tylko po podejrzeniu wycieku;
  • sprawdzaj hasło z listą skompromitowanych przy ustawianiu i zmianie.

isBreachedPassword() korzysta z API Have I Been Pwned w modelu k-anonimowości: wysyłasz tylko 5 pierwszych znaków skrótu SHA-1, a dopasowanie reszty robisz lokalnie – serwis nie wie, jakie hasło sprawdzasz. Nagłówek Add-Padding dokłada fałszywe wiersze, żeby nawet rozmiar odpowiedzi nic nie zdradzał.

Krok 3. Tokeny: JWT dostępu i nieprzezroczyste tokeny odświeżania

Serwis tokenów

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) };
}
  • Access token to JWT podpisany HS256 z sub (id użytkownika), role, iss, aud i exp. Weryfikacja przypina algorytm, wystawcę i odbiorcę – nie ufasz nagłówkowi tokena (klasyczny atak to alg: none albo podmiana RS256 na HS256).
  • Refresh token i linki z e-maili to 32 losowe bajty (base64url). Klient dostaje token, baza – tylko jego SHA-256. Wyciek kopii bazy nie pozwala przejąć sesji. Zwykły SHA-256 wystarcza, bo token ma 256 bitów entropii – w przeciwieństwie do haseł nie da się go zgadnąć.
  • HS256 czy RS256/EdDSA? Symetryczny klucz jest prosty, gdy tokeny wystawia i sprawdza ten sam serwis. Gdy weryfikuje je kilka serwisów, użyj klucza asymetrycznego i publikuj klucze publiczne (JWKS) – serwisy dostają tylko klucz publiczny i nie mogą podrabiać tokenów.

Krok 4. Magazyn, blokady i poczta

Model danych, ograniczanie prób i port poczty

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

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Krok 5. Serwis: rejestracja, weryfikacja, logowanie, rotacja, reset
  • Krok 6. HTTP: ciasteczka, middleware i trasy
  • Krok 7. Logowanie przez Google i GitHub (OAuth 2.0 i OpenID Connect)
  • Krok 8. Testy scenariuszy ataku
  • Wariant NestJS: globalny guard JWT
  • Lista kontrolna według OWASP ASVS 5.0
  • Typowe błędy
  • Sprawdź się
  • Co dalej

Załóż darmowe konto · Zaloguj się