{"id":"6b09417b5ce40d447918f27b","slug":"authentication","title":"Backend login and registration – passwords, sessions, JWT, refresh token rotation and OAuth","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"topics":["authentication","express","nestjs"],"techs":["node","typescript"],"tags":["argon2","jwt","refresh-token-rotation","cookies","csrf","oauth2","oidc","pkce","owasp-asvs","rate-limiting","password-reset"],"level":"advanced","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":37,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:19.171Z","updatedAt":"2026-11-27T13:05:06.179Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"Node.js authentication step by step – argon2id, NIST 800-63B, sessions vs JWT, access and refresh token in an httpOnly cookie, rotation and reuse detection, e-mail verification, password reset, rate limiting, OAuth 2.0/OIDC with PKCE (Google, GitHub), a JWT guard in NestJS and OWASP ASVS 5.0.","wordCount":7292,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"callout","attrs":{"variant":"info","title":"In a nutshell"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Passwords only as an argon2id hash","marks":[{"type":"bold"}]},{"type":"text","text":" with the salt and parameters in one string; the policy follows NIST SP 800-63B-4: length instead of \"uppercase plus special character\", and a check against breached passwords."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A short JWT (15 min) in the app's memory + a long, opaque refresh token in an ","marks":[{"type":"bold"}]},{"type":"text","text":"httpOnly; Secure; SameSite=Strict","marks":[{"type":"code"}]},{"type":"text","text":" cookie","marks":[{"type":"bold"}]},{"type":"text","text":". Every refresh swaps the refresh token for a new one, and reusing an old one revokes the whole session family."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Responses do not reveal who has an account","marks":[{"type":"bold"}]},{"type":"text","text":": registration, \"forgot password\" and a failed login look the same for existing and non-existing e-mails – timing included."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"pierogi-auth","marks":[{"type":"code"}]},{"type":"text","text":": registration with a verification link, login, session refresh with rotation, logout, password reset (logs out every device), a per-IP request limit and a growing lockout after failed attempts, role-protected endpoints and optional Google sign-in. Five tests cover attack scenarios: a stolen refresh token, account enumeration and password guessing. At the end, the same model in NestJS – a global guard with "},{"type":"text","text":"@Public()","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"@Roles()","marks":[{"type":"code"}]},{"type":"text","text":". Download the code (21 files) as a ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"REST API with Express 5","marks":[{"type":"link","attrs":{"href":"/en/articles/express"}}]},{"type":"text","text":" (project layout, error handling), HTTP basics: headers, cookies, CORS. For the NestJS variant – "},{"type":"text","text":"NestJS in practice","marks":[{"type":"link","attrs":{"href":"/en/articles/nestjs"}}]},{"type":"text","text":"."}]},{"type":"stats","attrs":{"items":[{"value":"19 MiB","label":"of memory per hash","hint":"argon2id as recommended by OWASP"},{"value":"15 min","label":"access token lifetime","hint":"a stateless JWT"},{"value":"30 days","label":"refresh token lifetime","hint":"rotated on every use"},{"value":"15","label":"characters minimum","hint":"NIST 800-63B-4 for password-only login"}]}},{"type":"heading","attrs":{"level":2,"id":"sessions-or-jwt"},"content":[{"type":"text","text":"Sessions or JWT?"}]},{"type":"paragraph","content":[{"type":"text","text":"This is the first question and the source of many misunderstandings. Both approaches work; they differ in where the state lives."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph"}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Server-side session"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"JWT only"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Hybrid (this tutorial)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"What the client holds"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a random session id in a cookie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a signed token with data"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a short JWT + a refresh token in a cookie"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Checking a request"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"read from Redis/database"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"signature check, no I/O"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"signature check, no I/O"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Logout, account lock"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"immediate"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"only after the token expires"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"within 15 min (refresh immediately)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Scaling, many services"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a shared session store"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"every service verifies itself"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"every service verifies itself"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"When"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"classic web app, one backend"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"service-to-service calls"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"SPA/mobile + API, several services"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Server-side sessions (e.g. "},{"type":"text","text":"express-session","marks":[{"type":"code"}]},{"type":"text","text":" with the "},{"type":"text","text":"connect-redis","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant B as Browser (SPA)\n  participant A as API /auth\n  participant DB as Token store\n  participant X as Attacker\n  B->>A: POST /auth/login (e-mail, password)\n  A->>DB: store hash(RT1), family F\n  A-->>B: accessToken (JSON) + Set-Cookie RT1 (httpOnly)\n  Note over B,A: 15 minutes later the access token expires\n  B->>A: POST /auth/refresh (Cookie RT1)\n  A->>DB: RT1 revoked, store hash(RT2) in F\n  A-->>B: new accessToken + Set-Cookie RT2\n  X->>A: POST /auth/refresh (stolen RT1)\n  A->>DB: RT1 already used – revoke the whole family F\n  A-->>X: 401 REFRESH_TOKEN_REUSED\n  B->>A: POST /auth/refresh (Cookie RT2)\n  A-->>B: 401 – sign in again","caption":"Login, refresh with rotation and detecting a stolen refresh token"}},{"type":"heading","attrs":{"level":2,"id":"step-1-the-project-and-configuration"},"content":[{"type":"text","text":"Step 1. The project and configuration"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm install express zod cookie-parser cors helmet express-rate-limit jose @node-rs/argon2 arctic\nnpm install -D typescript tsx vitest supertest @types/node @types/express @types/cookie-parser @types/cors @types/supertest"}]},{"type":"codeGroup","attrs":{"title":"Project configuration"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-auth\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"engines\": {\n    \"node\": \">=22.12\"\n  },\n  \"scripts\": {\n    \"dev\": \"tsx watch --env-file-if-exists=.env src/server.ts\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"start\": \"node --env-file-if-exists=.env dist/server.js\",\n    \"typecheck\": \"tsc --noEmit\",\n    \"test\": \"vitest run\"\n  },\n  \"dependencies\": {\n    \"@node-rs/argon2\": \"^2.2.2\",\n    \"arctic\": \"^3.7.0\",\n    \"cookie-parser\": \"^1.4.7\",\n    \"cors\": \"^2.8.6\",\n    \"express\": \"^5.3.0\",\n    \"express-rate-limit\": \"^8.7.5\",\n    \"helmet\": \"^8.3.0\",\n    \"jose\": \"^6.2.18\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/cookie-parser\": \"^1.4.10\",\n    \"@types/cors\": \"^2.8.19\",\n    \"@types/express\": \"^5.0.6\",\n    \"@types/node\": \"^24.19.4\",\n    \"@types/supertest\": \"^7.2.1\",\n    \"supertest\": \"^7.3.2\",\n    \"tsx\": \"^4.23.15\",\n    \"typescript\": \"^7.0.2\",\n    \"vitest\": \"^5.1.2\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"ES2024\",\n    \"module\": \"nodenext\",\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"verbatimModuleSyntax\": true,\n    \"skipLibCheck\": true,\n    \"sourceMap\": true,\n    \"noEmit\": true,\n    \"types\": [\"node\"]\n  },\n  \"include\": [\"src\", \"test\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.build.json"},"content":[{"type":"text","text":"{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": { \"noEmit\": false, \"rootDir\": \"src\", \"outDir\": \"dist\" },\n  \"include\": [\"src\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":".env.example"},"content":[{"type":"text","text":"NODE_ENV=development\nPORT=3000\nAPP_URL=http://localhost:5173\nAPI_URL=http://localhost:3000\nCORS_ORIGINS=http://localhost:5173\n# openssl rand -base64 48\nJWT_SECRET=replace-with-at-least-32-random-characters\nACCESS_TOKEN_TTL_SEC=900\nREFRESH_TOKEN_TTL_DAYS=30\n# Optional: Google sign-in (console.cloud.google.com -> Credentials -> OAuth client ID)\n# Authorized redirect URI: http://localhost:3000/auth/google/callback\nGOOGLE_CLIENT_ID=\nGOOGLE_CLIENT_SECRET="}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/config.ts"},"content":[{"type":"text","text":"import { z } from 'zod';\n\nconst EnvSchema = z.object({\n  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),\n  PORT: z.coerce.number().int().default(3000),\n  // Front-end URL used in e-mail links and OAuth redirects back to the app.\n  APP_URL: z.url().default('http://localhost:5173'),\n  API_URL: z.url().default('http://localhost:3000'),\n  CORS_ORIGINS: z\n    .string()\n    .default('http://localhost:5173')\n    .transform((v) => v.split(',').map((s) => s.trim())),\n  // openssl rand -base64 48 – at least 256 bits for HS256.\n  JWT_SECRET: z.string().min(32),\n  JWT_ISSUER: z.string().default('pierogi-api'),\n  JWT_AUDIENCE: z.string().default('pierogi-web'),\n  ACCESS_TOKEN_TTL_SEC: z.coerce.number().int().positive().default(900),\n  REFRESH_TOKEN_TTL_DAYS: z.coerce.number().int().positive().default(30),\n  GOOGLE_CLIENT_ID: z.string().optional(),\n  GOOGLE_CLIENT_SECRET: z.string().optional(),\n});\n\nexport type Config = z.infer<typeof EnvSchema>;\n\nexport function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {\n  const parsed = EnvSchema.safeParse(env);\n  if (!parsed.success) {\n    console.error(`Invalid environment configuration:\\n${z.prettifyError(parsed.error)}`);\n    process.exit(1);\n  }\n  return parsed.data;\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"JWT_SECRET","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"heading","attrs":{"level":2,"id":"step-2-passwords-argon2id-and-a-sensible-policy"},"content":[{"type":"text","text":"Step 2. Passwords: argon2id and a sensible policy"}]},{"type":"codeGroup","attrs":{"title":"Hashing, policy and breach checking"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/password.ts"},"content":[{"type":"text","text":"import { createHash } from 'node:crypto';\nimport { hash, parseOptions, verify } from '@node-rs/argon2';\nimport { z } from 'zod';\n\n// OWASP Password Storage Cheat Sheet: argon2id, 19 MiB of memory, 2 iterations, 1 lane.\nconst ARGON2 = { memoryCost: 19_456, timeCost: 2, parallelism: 1 };\n\n// NIST SP 800-63B-4: at least 15 characters for password-only login, no composition rules,\n// allow long passphrases. The upper bound only protects the server from huge inputs.\nexport const PasswordSchema = z.string().min(15, 'Use at least 15 characters – a passphrase works best').max(128);\n\nexport function hashPassword(plain: string): Promise<string> {\n  return hash(plain, ARGON2); // the salt is generated and stored inside the PHC string\n}\n\nexport function verifyPassword(stored: string, plain: string): Promise<boolean> {\n  return verify(stored, plain);\n}\n\n// True when the hash was created with weaker parameters than today's – rehash after login.\nexport function needsRehash(stored: string): boolean {\n  const current = parseOptions(stored);\n  return current.memoryCost < ARGON2.memoryCost || current.timeCost < ARGON2.timeCost;\n}\n\n// Verified against for unknown e-mails, so they take as long as a wrong password.\nexport const DUMMY_HASH = await hashPassword('timing-equalizer-not-a-real-password');\n\n// Have I Been Pwned \"range\" API with k-anonymity: only 5 hex chars of the SHA-1 leave the server.\nexport async function isBreachedPassword(plain: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n  const sha1 = createHash('sha1').update(plain).digest('hex').toUpperCase();\n  const prefix = sha1.slice(0, 5);\n  const suffix = sha1.slice(5);\n  try {\n    const res = await fetchImpl(`https://api.pwnedpasswords.com/range/${prefix}`, {\n      headers: { 'Add-Padding': 'true' },\n      signal: AbortSignal.timeout(2_000),\n    });\n    if (!res.ok) return false;\n    const body = await res.text();\n    return body.split('\\n').some((line) => {\n      const [hashSuffix, count] = line.trim().split(':');\n      return hashSuffix === suffix && Number(count) > 0; // padding rows have count 0\n    });\n  } catch {\n    return false; // fail open: an outage of the API must not block sign-ups\n  }\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Choosing the algorithm.","marks":[{"type":"bold"}]},{"type":"text","text":" 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."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Algorithm"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Status"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Notes"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"argon2id","marks":[{"type":"bold"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"first choice (OWASP)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"m=19 MiB, t=2, p=1; resistant to GPUs and side-channel attacks"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"scrypt"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"good"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"built into Node.js ("},{"type":"text","text":"crypto.scrypt","marks":[{"type":"code"}]},{"type":"text","text":") – a zero-dependency option"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"bcrypt"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"acceptable in legacy systems"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cost ≥ 10; "},{"type":"text","text":"truncates the password to 72 bytes","marks":[{"type":"bold"}]},{"type":"text","text":" – long passphrases lose their point"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"PBKDF2"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"when FIPS requires it"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"600,000 iterations for HMAC-SHA-256"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"MD5, SHA-1, SHA-256"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"never for passwords"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"billions of guesses per second on one card"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"@node-rs/argon2","marks":[{"type":"code"}]},{"type":"text","text":" 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 ("},{"type":"text","text":"$argon2id$v=19$m=19456,t=2,p=1$salt$hash","marks":[{"type":"code"}]},{"type":"text","text":"), so the parameters and the salt are stored with it. "},{"type":"text","text":"needsRehash()","marks":[{"type":"code"}]},{"type":"text","text":" lets you raise the parameters later: the password is rehashed on the next successful login."}]},{"type":"paragraph","content":[{"type":"text","text":"Password policy according to NIST SP 800-63B-4 (2025):","marks":[{"type":"bold"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"at least "},{"type":"text","text":"15 characters","marks":[{"type":"bold"}]},{"type":"text","text":" when the password is the only factor (8 if it is part of MFA), allow at least 64 characters;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"no composition rules","marks":[{"type":"bold"}]},{"type":"text","text":" (\"uppercase, digit, special character\") and "},{"type":"text","text":"no periodic changes","marks":[{"type":"bold"}]},{"type":"text","text":" – force a change only when a compromise is suspected;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"check the password against a list of compromised passwords","marks":[{"type":"bold"}]},{"type":"text","text":" when it is set or changed."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"isBreachedPassword()","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"Add-Padding","marks":[{"type":"code"}]},{"type":"text","text":" header adds fake rows so that even the response size reveals nothing."}]},{"type":"heading","attrs":{"level":2,"id":"step-3-tokens-access-jwts-and-opaque-refresh-tokens"},"content":[{"type":"text","text":"Step 3. Tokens: access JWTs and opaque refresh tokens"}]},{"type":"codeGroup","attrs":{"title":"Token service"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/tokens.ts"},"content":[{"type":"text","text":"import { createHash, randomBytes } from 'node:crypto';\nimport { errors, jwtVerify, SignJWT } from 'jose';\nimport type { Role } from './auth.store.js';\n\nexport interface AccessClaims {\n  sub: string;\n  role: Role;\n}\n\nexport interface TokenConfig {\n  secret: string;\n  issuer: string;\n  audience: string;\n  accessTtlSec: number;\n}\n\n// Short-lived, stateless access token (JWT). Revocation = wait up to accessTtlSec.\nexport class TokenService {\n  private readonly key: Uint8Array;\n\n  constructor(private readonly cfg: TokenConfig) {\n    this.key = new TextEncoder().encode(cfg.secret);\n  }\n\n  get accessTtlSec(): number {\n    return this.cfg.accessTtlSec;\n  }\n\n  signAccess(user: { id: string; role: Role }): Promise<string> {\n    return new SignJWT({ role: user.role })\n      .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })\n      .setSubject(user.id)\n      .setIssuer(this.cfg.issuer)\n      .setAudience(this.cfg.audience)\n      .setIssuedAt()\n      .setExpirationTime(`${this.cfg.accessTtlSec}s`)\n      .sign(this.key);\n  }\n\n  async verifyAccess(token: string): Promise<AccessClaims> {\n    // Pin the algorithm, issuer and audience – never trust the token's own header.\n    const { payload } = await jwtVerify(token, this.key, {\n      algorithms: ['HS256'],\n      issuer: this.cfg.issuer,\n      audience: this.cfg.audience,\n    });\n    if (typeof payload.sub !== 'string' || (payload.role !== 'customer' && payload.role !== 'staff')) {\n      throw new errors.JWTClaimValidationFailed('unexpected claims', payload);\n    }\n    return { sub: payload.sub, role: payload.role };\n  }\n}\n\nexport const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n// Opaque random tokens (refresh, e-mail links): the client gets `token`, the database only `hash`.\nexport function newOpaqueToken(): { token: string; hash: string } {\n  const token = randomBytes(32).toString('base64url');\n  return { token, hash: sha256(token) };\n}"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The access token","marks":[{"type":"bold"}]},{"type":"text","text":" is a JWT signed with HS256 containing "},{"type":"text","text":"sub","marks":[{"type":"code"}]},{"type":"text","text":" (the user id), "},{"type":"text","text":"role","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"iss","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"aud","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"exp","marks":[{"type":"code"}]},{"type":"text","text":". Verification "},{"type":"text","text":"pins the algorithm, issuer and audience","marks":[{"type":"bold"}]},{"type":"text","text":" – you do not trust the token's header (the classic attacks are "},{"type":"text","text":"alg: none","marks":[{"type":"code"}]},{"type":"text","text":" or swapping RS256 for HS256)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Refresh tokens and e-mail links","marks":[{"type":"bold"}]},{"type":"text","text":" are 32 random bytes ("},{"type":"text","text":"base64url","marks":[{"type":"code"}]},{"type":"text","text":"). 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."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"HS256 or RS256/EdDSA?","marks":[{"type":"bold"}]},{"type":"text","text":" 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."}]}]}]},{"type":"callout","attrs":{"variant":"warning","title":"Do not put anything into a JWT you would not show the user"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A JWT is signed, not encrypted – anyone can read its base64 content. No addresses, phone numbers or \"just in case\" permissions. The less data, the fewer problems when it changes before the token expires."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-4-storage-lockouts-and-mail"},"content":[{"type":"text","text":"Step 4. Storage, lockouts and mail"}]},{"type":"codeGroup","attrs":{"title":"Data model, attempt throttling and the mail port"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/auth.store.ts"},"content":[{"type":"text","text":"export type Role = 'customer' | 'staff';\n\nexport interface User {\n  id: string;\n  email: string; // normalized: trimmed, lower-case\n  passwordHash: string | null; // null for accounts created with Google\n  googleSub: string | null;\n  role: Role;\n  emailVerifiedAt: Date | null;\n  createdAt: Date;\n}\n\nexport interface RefreshToken {\n  id: string;\n  userId: string;\n  familyId: string; // all tokens rotated from one login\n  tokenHash: string;\n  expiresAt: Date;\n  revokedAt: Date | null;\n  replacedById: string | null;\n  userAgent?: string;\n}\n\nexport type OneTimePurpose = 'verify-email' | 'reset-password';\n\nexport interface OneTimeToken {\n  tokenHash: string;\n  userId: string;\n  purpose: OneTimePurpose;\n  expiresAt: Date;\n  usedAt: Date | null;\n}\n\n// In SQL: users(email UNIQUE), refresh_tokens(token_hash UNIQUE, family_id INDEX), one_time_tokens(token_hash UNIQUE).\nexport interface AuthStore {\n  findUserByEmail(email: string): Promise<User | undefined>;\n  findUserById(id: string): Promise<User | undefined>;\n  findUserByGoogleSub(sub: string): Promise<User | undefined>;\n  saveUser(user: User): Promise<void>;\n  saveRefreshToken(token: RefreshToken): Promise<void>;\n  findRefreshTokenByHash(hash: string): Promise<RefreshToken | undefined>;\n  revokeRefreshFamily(familyId: string, at: Date): Promise<void>;\n  revokeAllRefreshTokens(userId: string, at: Date): Promise<void>;\n  saveOneTimeToken(token: OneTimeToken): Promise<void>;\n  findOneTimeToken(hash: string, purpose: OneTimePurpose): Promise<OneTimeToken | undefined>;\n}\n\nexport class InMemoryAuthStore implements AuthStore {\n  private readonly users = new Map<string, User>();\n  private readonly refreshTokens = new Map<string, RefreshToken>();\n  private readonly oneTimeTokens = new Map<string, OneTimeToken>();\n\n  async findUserByEmail(email: string) {\n    return [...this.users.values()].find((u) => u.email === email);\n  }\n  async findUserById(id: string) {\n    return this.users.get(id);\n  }\n  async findUserByGoogleSub(sub: string) {\n    return [...this.users.values()].find((u) => u.googleSub === sub);\n  }\n  async saveUser(user: User) {\n    this.users.set(user.id, { ...user });\n  }\n  async saveRefreshToken(token: RefreshToken) {\n    this.refreshTokens.set(token.id, { ...token });\n  }\n  async findRefreshTokenByHash(hash: string) {\n    const token = [...this.refreshTokens.values()].find((t) => t.tokenHash === hash);\n    return token && { ...token };\n  }\n  async revokeRefreshFamily(familyId: string, at: Date) {\n    for (const t of this.refreshTokens.values()) if (t.familyId === familyId) t.revokedAt ??= at;\n  }\n  async revokeAllRefreshTokens(userId: string, at: Date) {\n    for (const t of this.refreshTokens.values()) if (t.userId === userId) t.revokedAt ??= at;\n  }\n  async saveOneTimeToken(token: OneTimeToken) {\n    this.oneTimeTokens.set(token.tokenHash, { ...token });\n  }\n  async findOneTimeToken(hash: string, purpose: OneTimePurpose) {\n    const token = this.oneTimeTokens.get(hash);\n    return token?.purpose === purpose ? { ...token } : undefined;\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/login-throttle.ts"},"content":[{"type":"text","text":"// Per-account throttling with exponential backoff, keyed by the normalized e-mail –\n// it behaves the same for existing and non-existing accounts (no user enumeration).\n// Single process only: with several instances keep the counters in Redis.\nexport class LoginThrottle {\n  private readonly failures = new Map<string, { count: number; lockedUntil: number }>();\n\n  constructor(\n    private readonly freeAttempts = 5,\n    private readonly maxLockMs = 15 * 60_000,\n    private readonly now: () => number = Date.now,\n  ) {}\n\n  retryAfterMs(key: string): number {\n    const entry = this.failures.get(key);\n    return entry ? Math.max(0, entry.lockedUntil - this.now()) : 0;\n  }\n\n  registerFailure(key: string): void {\n    const entry = this.failures.get(key) ?? { count: 0, lockedUntil: 0 };\n    entry.count += 1;\n    if (entry.count >= this.freeAttempts) {\n      // 30 s, 60 s, 120 s ... up to 15 minutes – a temporary lock, never a permanent one.\n      const lockMs = Math.min(this.maxLockMs, 30_000 * 2 ** (entry.count - this.freeAttempts));\n      entry.lockedUntil = this.now() + lockMs;\n    }\n    this.failures.set(key, entry);\n  }\n\n  reset(key: string): void {\n    this.failures.delete(key);\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/mailer.ts"},"content":[{"type":"text","text":"export interface MailMessage {\n  to: string;\n  subject: string;\n  text: string;\n}\n\n// Port: swap ConsoleMailer for an SES/SMTP adapter in production.\nexport interface Mailer {\n  send(message: MailMessage): Promise<void>;\n}\n\nexport class ConsoleMailer implements Mailer {\n  async send({ to, subject, text }: MailMessage): Promise<void> {\n    console.info(`[mail] to=${to} subject=\"${subject}\"\\n${text}\\n`);\n  }\n}"}]}]}]},"toc":[{"id":"sessions-or-jwt","text":"Sessions or JWT?","level":2,"locked":false},{"id":"step-1-the-project-and-configuration","text":"Step 1. The project and configuration","level":2,"locked":false},{"id":"step-2-passwords-argon2id-and-a-sensible-policy","text":"Step 2. Passwords: argon2id and a sensible policy","level":2,"locked":false},{"id":"step-3-tokens-access-jwts-and-opaque-refresh-tokens","text":"Step 3. Tokens: access JWTs and opaque refresh tokens","level":2,"locked":false},{"id":"step-4-storage-lockouts-and-mail","text":"Step 4. Storage, lockouts and mail","level":2,"locked":false},{"id":"step-5-the-service-registration-verification-login-rotation-reset","text":"Step 5. The service: registration, verification, login, rotation, reset","level":2,"locked":true},{"id":"step-6-http-cookies-middleware-and-routes","text":"Step 6. HTTP: cookies, middleware and routes","level":2,"locked":true},{"id":"step-7-signing-in-with-google-and-github-oauth-2-0-and-openid-connect","text":"Step 7. Signing in with Google and GitHub (OAuth 2.0 and OpenID Connect)","level":2,"locked":true},{"id":"step-8-testing-attack-scenarios","text":"Step 8. Testing attack scenarios","level":2,"locked":true},{"id":"the-nestjs-variant-a-global-jwt-guard","text":"The NestJS variant: a global JWT guard","level":2,"locked":true},{"id":"checklist-based-on-owasp-asvs-5-0","text":"Checklist based on OWASP ASVS 5.0","level":2,"locked":true},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":true},{"id":"check-yourself","text":"Check yourself","level":2,"locked":true},{"id":"what-s-next","text":"What's next","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":68,"visibleBlocks":28,"resources":[{"id":"6b0857c73c96f2d34d0b4926","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=J4ix8Mhi3rs","embedUrl":"https://www.youtube-nocookie.com/embed/J4ix8Mhi3rs","title":"Best Practices for Secure Password Hashing in .NET (Stop Storing Passwords in Plain Text!)","description":"Want to master Clean Architecture? Go here: https://bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: https://bit.ly/3SXlzSt Join a community of 1000+ .NET developers: https://www.patreon.com/milanjovanovic Never store passwords in plain text! In this video, you'll learn the essential…","author":"Milan Jovanović","thumbnailUrl":"https://i.ytimg.com/vi/J4ix8Mhi3rs/hqdefault.jpg","durationSec":null,"lang":"en","topics":["modular-monolith","clean-architecture"],"techs":["dotnet"],"tags":["security","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2024-08-16T11:00:28.000Z","popularity":65,"verifiedAt":"2026-11-26T10:54:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857bf3c96f2d34d0b42a9","type":"article","provider":"web","url":"https://learn.microsoft.com/en-us/azure/architecture/patterns/federated-identity","embedUrl":null,"title":"Federated Identity Pattern","description":"Use the Federated Identity design pattern to delegate authentication to an external identity provider.","author":"Microsoft Azure Architecture Center","thumbnailUrl":"https://learn.microsoft.com/en-us/media/open-graph-image.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["azure","cloud","design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":62,"verifiedAt":"2026-11-26T11:07:49.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c83c96f2d34d0b49ee","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=3611y9h-U-0","embedUrl":"https://www.youtube-nocookie.com/embed/3611y9h-U-0","title":"Building Secure Microservices in Azure - Jimmy Bogard - NDC London 2023","description":"Building microservices can be easy, but securing them is hard. We have external and internal applications, APIs, queues, users, and more. Each might use a different authentication and authorization strategy, depending on customer and system needs. The stakes are high and there is no margin for…","author":"NDC Conferences","thumbnailUrl":"https://i.ytimg.com/vi/3611y9h-U-0/hqdefault.jpg","durationSec":null,"lang":"en","topics":["microservices"],"techs":["general"],"tags":["cloud","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2023-05-14T15:00:02.000Z","popularity":59,"verifiedAt":"2026-11-26T11:13:14.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857c53c96f2d34d0b484f","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=6DWJIyipxzw","embedUrl":"https://www.youtube-nocookie.com/embed/6DWJIyipxzw","title":"Secure Your .NET API in 15 Minutes: JWT Authentication Tutorial","description":"Get the source code for this video for FREE → https://the-dotnet-weekly.kit.com/secure-dotnet Want to master Clean Architecture? Go here: https://bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: https://bit.ly/3SXlzSt Join a community of 1000+ .NET developers…","author":"Milan Jovanović","thumbnailUrl":"https://i.ytimg.com/vi/6DWJIyipxzw/hqdefault.jpg","durationSec":null,"lang":"en","topics":["modular-monolith","clean-architecture"],"techs":["dotnet"],"tags":["software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2024-08-30T11:00:05.000Z","popularity":75,"verifiedAt":"2026-11-26T10:54:06.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}