{"id":"6b09417b5ce40d447918f27b","slug":"authentication","title":"Logowanie i rejestracja na backendzie – hasła, sesje, JWT, rotacja refresh tokenów i OAuth","summary":"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.","servedLang":"pl","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":35,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:19.171Z","updatedAt":"2026-11-27T10:04:57.726Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"Uwierzytelnianie w Node.js krok po kroku – argon2id, NIST 800-63B, sesje vs JWT, access i refresh token w ciasteczku httpOnly, rotacja i reuse detection, weryfikacja e-mail, reset hasła, rate limiting, OAuth 2.0/OIDC z PKCE (Google, GitHub), guard JWT w NestJS i OWASP ASVS 5.0.","wordCount":6973,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Hasła tylko jako skrót argon2id","marks":[{"type":"bold"}]},{"type":"text","text":" z solą i parametrami w jednym napisie; polityka według NIST SP 800-63B-4: długość zamiast „wielka litera i znak specjalny”, sprawdzanie haseł z wycieków."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Krótki JWT (15 min) w pamięci aplikacji + długi, nieprzezroczysty refresh token w ciasteczku ","marks":[{"type":"bold"}]},{"type":"text","text":"httpOnly; Secure; SameSite=Strict","marks":[{"type":"code"}]},{"type":"text","text":". Każde odświeżenie wymienia refresh token na nowy, a ponowne użycie starego unieważnia całą rodzinę sesji."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Odpowiedzi nie zdradzają, kto ma konto","marks":[{"type":"bold"}]},{"type":"text","text":": rejestracja, „nie pamiętam hasła” i błędne logowanie wyglądają tak samo dla istniejącego i nieistniejącego e-maila – także czasowo."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"pierogi-auth","marks":[{"type":"code"}]},{"type":"text","text":": rejestracja z linkiem weryfikacyjnym, logowanie, odświeżanie sesji z rotacją, wylogowanie, reset hasła (wylogowuje wszystkie urządzenia), limit żądań na IP i rosnąca blokada po nieudanych próbach, endpointy chronione rolą, opcjonalne logowanie przez Google. Pięć testów sprawdza scenariusze ataku: kradzież refresh tokena, enumerację kont i zgadywanie haseł. Na końcu ten sam model w NestJS – globalny guard z "},{"type":"text","text":"@Public()","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"@Roles()","marks":[{"type":"code"}]},{"type":"text","text":". Kod (21 plików) pobierzesz jako ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"REST API w Express 5","marks":[{"type":"link","attrs":{"href":"/pl/articles/express"}}]},{"type":"text","text":" (struktura projektu, obsługa błędów), podstawy HTTP: nagłówki, ciasteczka, CORS. Dla wariantu NestJS – "},{"type":"text","text":"NestJS w praktyce","marks":[{"type":"link","attrs":{"href":"/pl/articles/nestjs"}}]},{"type":"text","text":"."}]},{"type":"stats","attrs":{"items":[{"value":"19 MiB","label":"pamięci na jedno haszowanie","hint":"argon2id według OWASP"},{"value":"15 min","label":"życia access tokena","hint":"JWT bez stanu"},{"value":"30 dni","label":"życia refresh tokena","hint":"rotowany przy każdym użyciu"},{"value":"15","label":"znaków minimum","hint":"NIST 800-63B-4 dla logowania samym hasłem"}]}},{"type":"heading","attrs":{"level":2,"id":"sesje-czy-jwt"},"content":[{"type":"text","text":"Sesje czy JWT?"}]},{"type":"paragraph","content":[{"type":"text","text":"To pierwsze pytanie i źródło wielu nieporozumień. Oba podejścia działają; różnią się tym, gdzie żyje stan."}]},{"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":"Sesja po stronie serwera"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Sam JWT"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Hybryda (ten poradnik)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Co ma klient"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"losowy identyfikator sesji w ciasteczku"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"podpisany token z danymi"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"krótki JWT + refresh token w ciasteczku"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Sprawdzenie żądania"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"odczyt z Redisa/bazy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"weryfikacja podpisu, bez I/O"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"weryfikacja podpisu, bez I/O"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wylogowanie, blokada konta"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"natychmiast"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dopiero po wygaśnięciu tokena"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"po maks. 15 min (refresh od razu)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Skalowanie, wiele serwisów"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wspólny magazyn sesji"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"każdy serwis sam weryfikuje"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"każdy serwis sam weryfikuje"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kiedy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"klasyczna aplikacja webowa, jeden backend"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"komunikacja serwis–serwis"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"SPA/mobile + API, kilka serwisów"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Sesje po stronie serwera (np. "},{"type":"text","text":"express-session","marks":[{"type":"code"}]},{"type":"text","text":" z magazynem "},{"type":"text","text":"connect-redis","marks":[{"type":"code"}]},{"type":"text","text":") 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ć."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant B as Przeglądarka (SPA)\n  participant A as API /auth\n  participant DB as Baza tokenów\n  participant X as Atakujący\n  B->>A: POST /auth/login (e-mail, hasło)\n  A->>DB: zapisz hash(RT1), rodzina F\n  A-->>B: accessToken (JSON) + Set-Cookie RT1 (httpOnly)\n  Note over B,A: 15 minut później access token wygasa\n  B->>A: POST /auth/refresh (Cookie RT1)\n  A->>DB: RT1 unieważniony, zapisz hash(RT2) w F\n  A-->>B: nowy accessToken + Set-Cookie RT2\n  X->>A: POST /auth/refresh (skradziony RT1)\n  A->>DB: RT1 już użyty – unieważnij całą rodzinę F\n  A-->>X: 401 REFRESH_TOKEN_REUSED\n  B->>A: POST /auth/refresh (Cookie RT2)\n  A-->>B: 401 – zaloguj się ponownie","caption":"Logowanie, odświeżanie z rotacją i wykrycie kradzieży refresh tokena"}},{"type":"heading","attrs":{"level":2,"id":"krok-1-projekt-i-konfiguracja"},"content":[{"type":"text","text":"Krok 1. Projekt i konfiguracja"}]},{"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":"Konfiguracja projektu"},"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":" 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."}]},{"type":"heading","attrs":{"level":2,"id":"krok-2-hasla-argon2id-i-rozsadna-polityka"},"content":[{"type":"text","text":"Krok 2. Hasła: argon2id i rozsądna polityka"}]},{"type":"codeGroup","attrs":{"title":"Haszowanie, polityka i sprawdzanie wycieków"},"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":"Wybór algorytmu.","marks":[{"type":"bold"}]},{"type":"text","text":" 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."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Algorytm"}]}]},{"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":"Uwagi"}]}]}]},{"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":"pierwszy wybór (OWASP)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"m=19 MiB, t=2, p=1; odporny na GPU i ataki bocznym kanałem"}]}]}]},{"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":"dobry"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wbudowany w Node.js ("},{"type":"text","text":"crypto.scrypt","marks":[{"type":"code"}]},{"type":"text","text":") – opcja bez zależności"}]}]}]},{"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":"akceptowalny w starszych systemach"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"koszt ≥ 10; "},{"type":"text","text":"ucina hasło do 72 bajtów","marks":[{"type":"bold"}]},{"type":"text","text":" – długie frazy tracą sens"}]}]}]},{"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":"gdy wymaga tego FIPS"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"600 000 iteracji dla 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":"nigdy dla haseł"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"miliardy prób na sekundę na jednej karcie"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"@node-rs/argon2","marks":[{"type":"code"}]},{"type":"text","text":" 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 ("},{"type":"text","text":"$argon2id$v=19$m=19456,t=2,p=1$sól$skrót","marks":[{"type":"code"}]},{"type":"text","text":"), więc parametry i sól są zapisane razem z nim. "},{"type":"text","text":"needsRehash()","marks":[{"type":"code"}]},{"type":"text","text":" pozwala podnieść parametry w przyszłości: przy najbliższym udanym logowaniu hasło zostanie zahaszowane ponownie."}]},{"type":"paragraph","content":[{"type":"text","text":"Polityka haseł według NIST SP 800-63B-4 (2025):","marks":[{"type":"bold"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"minimum "},{"type":"text","text":"15 znaków","marks":[{"type":"bold"}]},{"type":"text","text":", gdy hasło jest jedynym czynnikiem (8, jeśli jest częścią MFA), pozwól na co najmniej 64 znaki;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"żadnych reguł złożoności","marks":[{"type":"bold"}]},{"type":"text","text":" („wielka litera, cyfra, znak specjalny”) i "},{"type":"text","text":"żadnej okresowej zmiany","marks":[{"type":"bold"}]},{"type":"text","text":" – wymuszaj zmianę tylko po podejrzeniu wycieku;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"sprawdzaj hasło z listą skompromitowanych","marks":[{"type":"bold"}]},{"type":"text","text":" przy ustawianiu i zmianie."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"isBreachedPassword()","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"Add-Padding","marks":[{"type":"code"}]},{"type":"text","text":" dokłada fałszywe wiersze, żeby nawet rozmiar odpowiedzi nic nie zdradzał."}]},{"type":"heading","attrs":{"level":2,"id":"krok-3-tokeny-jwt-dostepu-i-nieprzezroczyste-tokeny-odswiezania"},"content":[{"type":"text","text":"Krok 3. Tokeny: JWT dostępu i nieprzezroczyste tokeny odświeżania"}]},{"type":"codeGroup","attrs":{"title":"Serwis tokenów"},"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":"Access token","marks":[{"type":"bold"}]},{"type":"text","text":" to JWT podpisany HS256 z "},{"type":"text","text":"sub","marks":[{"type":"code"}]},{"type":"text","text":" (id użytkownika), "},{"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":" i "},{"type":"text","text":"exp","marks":[{"type":"code"}]},{"type":"text","text":". Weryfikacja "},{"type":"text","text":"przypina algorytm, wystawcę i odbiorcę","marks":[{"type":"bold"}]},{"type":"text","text":" – nie ufasz nagłówkowi tokena (klasyczny atak to "},{"type":"text","text":"alg: none","marks":[{"type":"code"}]},{"type":"text","text":" albo podmiana RS256 na HS256)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Refresh token i linki z e-maili","marks":[{"type":"bold"}]},{"type":"text","text":" to 32 losowe bajty ("},{"type":"text","text":"base64url","marks":[{"type":"code"}]},{"type":"text","text":"). 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ąć."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"HS256 czy RS256/EdDSA?","marks":[{"type":"bold"}]},{"type":"text","text":" 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."}]}]}]},{"type":"callout","attrs":{"variant":"warning","title":"Nie wkładaj do JWT tego, czego nie pokazałbyś użytkownikowi"},"content":[{"type":"paragraph","content":[{"type":"text","text":"JWT jest podpisany, nie zaszyfrowany – każdy odczyta jego zawartość w base64. Bez adresów, numerów telefonów i uprawnień „na zapas”. Im mniej danych, tym mniej problemów, gdy się zmienią przed wygaśnięciem tokena."}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-4-magazyn-blokady-i-poczta"},"content":[{"type":"text","text":"Krok 4. Magazyn, blokady i poczta"}]},{"type":"codeGroup","attrs":{"title":"Model danych, ograniczanie prób i port poczty"},"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":"sesje-czy-jwt","text":"Sesje czy JWT?","level":2,"locked":false},{"id":"krok-1-projekt-i-konfiguracja","text":"Krok 1. Projekt i konfiguracja","level":2,"locked":false},{"id":"krok-2-hasla-argon2id-i-rozsadna-polityka","text":"Krok 2. Hasła: argon2id i rozsądna polityka","level":2,"locked":false},{"id":"krok-3-tokeny-jwt-dostepu-i-nieprzezroczyste-tokeny-odswiezania","text":"Krok 3. Tokeny: JWT dostępu i nieprzezroczyste tokeny odświeżania","level":2,"locked":false},{"id":"krok-4-magazyn-blokady-i-poczta","text":"Krok 4. Magazyn, blokady i poczta","level":2,"locked":false},{"id":"krok-5-serwis-rejestracja-weryfikacja-logowanie-rotacja-reset","text":"Krok 5. Serwis: rejestracja, weryfikacja, logowanie, rotacja, reset","level":2,"locked":true},{"id":"krok-6-http-ciasteczka-middleware-i-trasy","text":"Krok 6. HTTP: ciasteczka, middleware i trasy","level":2,"locked":true},{"id":"krok-7-logowanie-przez-google-i-github-oauth-2-0-i-openid-connect","text":"Krok 7. Logowanie przez Google i GitHub (OAuth 2.0 i OpenID Connect)","level":2,"locked":true},{"id":"krok-8-testy-scenariuszy-ataku","text":"Krok 8. Testy scenariuszy ataku","level":2,"locked":true},{"id":"wariant-nestjs-globalny-guard-jwt","text":"Wariant NestJS: globalny guard JWT","level":2,"locked":true},{"id":"lista-kontrolna-wedlug-owasp-asvs-5-0","text":"Lista kontrolna według OWASP ASVS 5.0","level":2,"locked":true},{"id":"typowe-bledy","text":"Typowe błędy","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","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":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}