{"id":"6b09417f5ce40d447918f2df","slug":"react-auth","title":"Logowanie i rejestracja w React – formularze, tokeny, chronione trasy i odświeżanie sesji","summary":"Kompletny frontend uwierzytelniania w React 19 – formularze logowania i rejestracji z walidacją, access token w pamięci i refresh token w ciasteczku httpOnly, przywracanie sesji, chronione trasy, ponawianie żądań po 401, reset hasła i logowanie przez Google – z działającym API demonstracyjnym.","servedLang":"pl","availableLangs":["pl","en"],"topics":["authentication","react"],"techs":["typescript","javascript","node"],"tags":["login","registration","refresh-token","httponly-cookie","protected-routes","oauth","password-reset","react-hook-form","zod","react-router"],"level":"intermediate","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":29,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:23.689Z","updatedAt":"2026-11-27T10:04:15.687Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"hex","weaveResources":true,"toc":"right"},"seoDescription":"Logowanie i rejestracja w React krok po kroku – react-hook-form + Zod, access token w pamięci, refresh token w ciasteczku httpOnly SameSite, rotacja, single-flight refresh i retry po 401, chronione trasy w React Router 8, reset hasła bez ujawniania kont, logowanie przez Google (OAuth) i typowe błędy","wordCount":5752,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Formularz logowania to kilka pól i przycisk, ale za nim stoi kilka decyzji, od których zależy bezpieczeństwo: gdzie trzymać token, co zrobić, gdy wygaśnie w połowie wysyłania zamówienia, jak przywrócić sesję po odświeżeniu strony i jak nie zdradzić, czy dany e-mail ma konto. W tym poradniku zbudujesz pełny frontend uwierzytelniania dla aplikacji pierogarni – z małym API w Expressie, żeby wszystko działało od razu po "},{"type":"text","text":"npm run dev","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Access token w pamięci, refresh token w ciasteczku ","marks":[{"type":"bold"}]},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":".","marks":[{"type":"bold"}]},{"type":"text","text":" JavaScript (także wstrzyknięty przez atak XSS) nie odczyta refresh tokena, a krótko żyjący access token znika po zamknięciu karty. Sesję po przeładowaniu przywraca jedno wywołanie "},{"type":"text","text":"/auth/refresh","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Jedno odświeżenie na wiele błędów 401.","marks":[{"type":"bold"}]},{"type":"text","text":" Klient API przy 401 odświeża token raz (single-flight) i ponawia żądanie. Gdy odświeżenie się nie uda, cała aplikacja przechodzi w stan „wylogowany”, a cache zapytań jest czyszczony."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Ochrona tras w React to wygoda, nie bezpieczeństwo.","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"RequireAuth","marks":[{"type":"code"}]},{"type":"text","text":" przekierowuje do logowania i z powrotem, ale dane chroni wyłącznie serwer, sprawdzając token przy każdym żądaniu."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Aplikację w Vite + React 19 + React Router 8 + TanStack Query: rejestracja z walidacją hasła i podglądem jego długości, logowanie z powrotem na stronę, z której przyszedł użytkownik, chroniona strona „My account” z zamówieniami, przycisk symulujący wygaśnięcie tokena (żeby zobaczyć 401 → refresh → retry w zakładce Network), wylogowanie, reset hasła z linkiem wypisywanym w terminalu i przycisk „Continue with Google” z kompletnym przepływem przekierowań. API demonstracyjne (Express) działa w tym samym serwerze deweloperskim. Kod (20 plików) pobierzesz jako ZIP ikoną przy artykule."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" React z hookami, react-hook-form i TanStack Query (zob. "},{"type":"text","text":"poradnik React","marks":[{"type":"link","attrs":{"href":"/pl/articles/react"}}]},{"type":"text","text":"), podstawy HTTP (nagłówki, ciasteczka, kody statusu). Backend opisujemy tylko w zakresie potrzebnym frontendowi – szczegóły w temacie "},{"type":"text","text":"Uwierzytelnianie","marks":[{"type":"link","attrs":{"href":"/pl/topics/authentication"}}]},{"type":"text","text":"."}]},{"type":"stats","attrs":{"items":[{"value":"30 s","label":"czas życia access tokena w demo","hint":"żeby zobaczyć odświeżanie na żywo"},{"value":"0","label":"tokenów w localStorage","hint":"access w pamięci, refresh w ciasteczku httpOnly"},{"value":"1","label":"wywołanie /refresh","hint":"nawet gdy 10 żądań dostanie 401 naraz"},{"value":"9","label":"przepływów sprawdzonych w przeglądarce","hint":"od rejestracji po logowanie przez Google"}]}},{"type":"heading","attrs":{"level":2,"id":"gdzie-trzymac-tokeny"},"content":[{"type":"text","text":"Gdzie trzymać tokeny"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Miejsce"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Odporność na XSS"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"CSRF"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Sesja po przeładowaniu"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Ocena"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"sessionStorage","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"brak – każdy skrypt odczyta token"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"brak ryzyka"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wygodne, ale wyciek tokena przy pierwszym XSS"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zwykłe ciasteczko (bez "},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"brak"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"trzeba chronić"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"najgorsze z obu światów"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"access w pamięci + refresh w ciasteczku ","marks":[{"type":"bold"}]},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"refresh nieczytelny dla JS, access krótki"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"SameSite=Strict","marks":[{"type":"code"}]},{"type":"text","text":" + ścieżka "},{"type":"text","text":"/api/auth","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak, przez "},{"type":"text","text":"/refresh","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dobry kompromis dla SPA – ten poradnik","marks":[{"type":"bold"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"sesja serwerowa / BFF (tylko ciasteczko "},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"token w ogóle nie trafia do przeglądarki"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"trzeba chronić"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"najbezpieczniejsze, wymaga backendu „dla frontendu”"}]}]}]}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant U as Użytkownik\n  participant R as React (pamięć)\n  participant A as API\n  U->>R: e-mail + hasło\n  R->>A: POST /api/auth/login\n  A-->>R: 200 accessToken (JSON) + Set-Cookie refresh_token (httpOnly)\n  R->>A: GET /api/orders (Authorization: Bearer …)\n  A-->>R: 200 zamówienia\n  Note over R,A: po 30 s access token wygasa\n  R->>A: GET /api/orders (stary token)\n  A-->>R: 401 TOKEN_EXPIRED\n  R->>A: POST /api/auth/refresh (ciasteczko wysyła przeglądarka)\n  A-->>R: 200 nowy accessToken + nowe ciasteczko (rotacja)\n  R->>A: GET /api/orders (nowy token) – ponowienie\n  A-->>R: 200 zamówienia","caption":"Logowanie, wygaśnięcie access tokena i ciche odświeżenie"}},{"type":"heading","attrs":{"level":2,"id":"krok-1-projekt-i-api-demonstracyjne"},"content":[{"type":"text","text":"Krok 1. Projekt i API demonstracyjne"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm create vite@latest pierogi-auth -- --template react-ts\ncd pierogi-auth\nnpm install react-router @tanstack/react-query react-hook-form @hookform/resolvers zod\nnpm install -D express cookie-parser @types/express @types/cookie-parser @types/node"}]},{"type":"paragraph","content":[{"type":"text","text":"Aplikacja Express jest podpięta do serwera deweloperskiego Vite jako middleware ("},{"type":"text","text":"configureServer","marks":[{"type":"code"}]},{"type":"text","text":"). Frontend i API mają ten sam origin, więc ciasteczka działają bez konfiguracji CORS. Na produkcji ta sama aplikacja Express (albo Twój backend w NestJS, .NET czy Go) stoi za tym samym reverse proxy co frontend."}]},{"type":"codeGroup","attrs":{"title":"Konfiguracja projektu"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-auth\",\n  \"private\": true,\n  \"version\": \"0.1.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc --noEmit && vite build\"\n  },\n  \"dependencies\": {\n    \"@hookform/resolvers\": \"^7.0.9\",\n    \"@tanstack/react-query\": \"^5.108.4\",\n    \"react\": \"^19.3.1\",\n    \"react-dom\": \"^19.3.1\",\n    \"react-hook-form\": \"^7.92.0\",\n    \"react-router\": \"^8.5.3\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/cookie-parser\": \"^1.4.10\",\n    \"@types/express\": \"^5.0.6\",\n    \"@types/node\": \"^24.0.0\",\n    \"@types/react\": \"^19.3.0\",\n    \"@types/react-dom\": \"^19.3.0\",\n    \"@vitejs/plugin-react\": \"^6.3.0\",\n    \"cookie-parser\": \"^1.4.7\",\n    \"express\": \"^5.3.0\",\n    \"typescript\": \"~7.0.2\",\n    \"vite\": \"^8.4.0\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"es2023\",\n    \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"bundler\",\n    \"types\": [\"vite/client\", \"node\"],\n    \"jsx\": \"react-jsx\",\n    \"noEmit\": true,\n    \"allowImportingTsExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"skipLibCheck\": true,\n    \"noUncheckedIndexedAccess\": true\n  },\n  \"include\": [\"src\", \"server\", \"vite.config.ts\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"vite.config.ts"},"content":[{"type":"text","text":"import react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\nimport { createAuthApi } from \"./server/auth-api.ts\";\n\n// The demo API runs inside the Vite dev server (same origin = simple cookies, no CORS).\n// In production the same Express app runs on its own behind your reverse proxy.\nexport default defineConfig({\n  plugins: [\n    react(),\n    {\n      name: \"auth-api\",\n      configureServer(server) {\n        server.middlewares.use(createAuthApi());\n      },\n    },\n  ],\n});"}]},{"type":"codeBlock","attrs":{"language":"html","filename":"index.html"},"content":[{"type":"text","text":"<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Pierogarnia · Account</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>"}]},{"type":"codeBlock","attrs":{"language":"css","filename":"src/index.css"},"content":[{"type":"text","text":"* { box-sizing: border-box; }\nbody { margin: 0; font-family: system-ui, sans-serif; color: #1f2328; background: #f6f7f9; }\na { color: #c2255c; }\n.shell { max-width: 720px; margin: 0 auto; padding: 16px; }\n.topbar { display: flex; gap: 16px; align-items: center; padding: 12px 0 16px; border-bottom: 1px solid #dee2e6; margin-bottom: 24px; }\n.topbar .spacer { flex: 1; }\n.card { background: #fff; border: 1px solid #dee2e6; border-radius: 12px; padding: 24px; max-width: 420px; margin: 0 auto; display: grid; gap: 14px; }\n.field { display: grid; gap: 4px; }\n.field input { padding: 9px 10px; border: 1px solid #ced4da; border-radius: 8px; font: inherit; }\n.field input[aria-invalid=\"true\"] { border-color: #c92a2a; }\n.password { display: grid; grid-template-columns: 1fr auto; gap: 6px; }\n.error { color: #c92a2a; font-size: 0.875rem; margin: 0; }\n.notice { background: #ebfbee; border: 1px solid #b2f2bb; padding: 10px 12px; border-radius: 8px; margin: 0; }\n.alert { background: #fff5f5; border: 1px solid #ffc9c9; padding: 10px 12px; border-radius: 8px; margin: 0; }\n.muted { color: #6c757d; font-size: 0.875rem; }\nbutton, .button { padding: 9px 14px; border-radius: 8px; border: 1px solid #c2255c; background: #c2255c; color: #fff; font: inherit; cursor: pointer; text-decoration: none; text-align: center; }\nbutton.secondary, .button.secondary { background: #fff; color: #1f2328; border-color: #ced4da; }\nbutton:disabled { opacity: 0.6; cursor: wait; }\n.divider { display: flex; align-items: center; gap: 8px; color: #6c757d; font-size: 0.875rem; }\n.divider::before, .divider::after { content: \"\"; flex: 1; border-top: 1px solid #dee2e6; }"}]}]},{"type":"paragraph","content":[{"type":"text","text":"API ma kształt produkcyjny, choć przechowuje dane w pamięci: hasła haszowane "},{"type":"text","text":"scrypt","marks":[{"type":"code"}]},{"type":"text","text":", access token w odpowiedzi JSON, refresh token w ciasteczku "},{"type":"text","text":"httpOnly","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"SameSite=Strict","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"path=/api/auth","marks":[{"type":"code"}]},{"type":"text","text":", rotacja refresh tokena przy każdym odświeżeniu i reset hasła, który wylogowuje ze wszystkich urządzeń."}]},{"type":"codeGroup","attrs":{"title":"Express: rejestracja, logowanie, refresh, reset hasła, OAuth"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"server/auth-api.ts"},"content":[{"type":"text","text":"// A minimal, in-memory auth API for the tutorial. The flows and cookie flags are production-shaped;\n// the storage (Maps) and the fake Google provider are not.\nimport cookieParser from \"cookie-parser\";\nimport express, { type NextFunction, type Request, type Response } from \"express\";\nimport { randomBytes, randomUUID, scryptSync, timingSafeEqual } from \"node:crypto\";\n\ntype User = { id: string; name: string; email: string; passwordHash: string | null };\ntype Grant = { userId: string; expiresAt: number };\n\nconst usersByEmail = new Map<string, User>();\nconst accessTokens = new Map<string, Grant>();\nconst refreshTokens = new Map<string, Grant>();\nconst resetTokens = new Map<string, Grant>();\n\nconst ACCESS_TTL_MS = 30_000; // deliberately short: watch the silent refresh in the Network tab\nconst REFRESH_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst REFRESH_COOKIE = \"refresh_token\";\n\nfunction hashPassword(password: string): string {\n  const salt = randomBytes(16);\n  return `${salt.toString(\"hex\")}:${scryptSync(password, salt, 32).toString(\"hex\")}`;\n}\n\nfunction verifyPassword(password: string, stored: string | null): boolean {\n  const [salt, hash] = (stored ?? \"\").split(\":\");\n  if (!salt || !hash) return false;\n  return timingSafeEqual(Buffer.from(hash, \"hex\"), scryptSync(password, Buffer.from(salt, \"hex\"), 32));\n}\n\nconst publicUser = (u: User) => ({ id: u.id, name: u.name, email: u.email });\nconst findUserById = (id: string) => [...usersByEmail.values()].find((u) => u.id === id);\n\n// Access token goes into the JSON body (kept in memory by the SPA);\n// refresh token goes into an httpOnly cookie that JavaScript can't read.\nfunction issueSession(res: Response, user: User) {\n  const accessToken = randomUUID();\n  accessTokens.set(accessToken, { userId: user.id, expiresAt: Date.now() + ACCESS_TTL_MS });\n  const refreshToken = randomBytes(32).toString(\"base64url\");\n  refreshTokens.set(refreshToken, { userId: user.id, expiresAt: Date.now() + REFRESH_TTL_MS });\n  res.cookie(REFRESH_COOKIE, refreshToken, {\n    httpOnly: true,\n    secure: process.env.NODE_ENV === \"production\",\n    sameSite: \"strict\",\n    path: \"/api/auth\", // the cookie is sent only to auth endpoints\n    maxAge: REFRESH_TTL_MS,\n  });\n  return { accessToken, expiresIn: ACCESS_TTL_MS / 1000, user: publicUser(user) };\n}\n\nfunction requireAuth(req: Request, res: Response, next: NextFunction) {\n  const token = req.headers.authorization?.replace(/^Bearer /, \"\");\n  const grant = token ? accessTokens.get(token) : undefined;\n  if (!grant || grant.expiresAt < Date.now()) {\n    res.status(401).json({ code: grant ? \"TOKEN_EXPIRED\" : \"UNAUTHORIZED\", message: \"Authentication required\" });\n    return;\n  }\n  res.locals.userId = grant.userId;\n  next();\n}\n\nexport function createAuthApi() {\n  const app = express();\n  app.use(\"/api\", express.json(), cookieParser());\n\n  app.post(\"/api/auth/register\", (req, res) => {\n    const { name, email, password } = req.body as { name?: string; email?: string; password?: string };\n    if (!name || !email || !password || password.length < 10) {\n      res.status(400).json({ code: \"VALIDATION_FAILED\", message: \"Invalid data\" });\n      return;\n    }\n    const key = email.toLowerCase();\n    if (usersByEmail.has(key)) {\n      res.status(409).json({ code: \"EMAIL_TAKEN\", message: \"An account with this email already exists\" });\n      return;\n    }\n    const user: User = { id: randomUUID(), name, email: key, passwordHash: hashPassword(password) };\n    usersByEmail.set(key, user);\n    res.status(201).json(issueSession(res, user));\n  });\n\n  app.post(\"/api/auth/login\", (req, res) => {\n    const { email, password } = req.body as { email?: string; password?: string };\n    const user = usersByEmail.get((email ?? \"\").toLowerCase());\n    // Same error for \"no such user\" and \"wrong password\" – no account enumeration.\n    if (!user || !verifyPassword(password ?? \"\", user.passwordHash)) {\n      res.status(401).json({ code: \"INVALID_CREDENTIALS\", message: \"Wrong email or password\" });\n      return;\n    }\n    res.json(issueSession(res, user));\n  });\n\n  // Rotation: every refresh invalidates the old refresh token and sets a new cookie.\n  app.post(\"/api/auth/refresh\", (req, res) => {\n    const token: string | undefined = req.cookies?.[REFRESH_COOKIE];\n    const grant = token ? refreshTokens.get(token) : undefined;\n    if (token) refreshTokens.delete(token);\n    const user = grant && grant.expiresAt > Date.now() ? findUserById(grant.userId) : undefined;\n    if (!user) {\n      res.clearCookie(REFRESH_COOKIE, { path: \"/api/auth\" });\n      res.status(401).json({ code: \"NO_SESSION\", message: \"Please sign in\" });\n      return;\n    }\n    res.json(issueSession(res, user));\n  });\n\n  app.post(\"/api/auth/logout\", (req, res) => {\n    const token: string | undefined = req.cookies?.[REFRESH_COOKIE];\n    if (token) refreshTokens.delete(token);\n    res.clearCookie(REFRESH_COOKIE, { path: \"/api/auth\" });\n    res.status(204).end();\n  });\n\n  // Always 204 – the response must not reveal whether the email has an account.\n  app.post(\"/api/auth/forgot-password\", (req, res) => {\n    const user = usersByEmail.get(String(req.body?.email ?? \"\").toLowerCase());\n    if (user) {\n      const token = randomBytes(32).toString(\"base64url\");\n      resetTokens.set(token, { userId: user.id, expiresAt: Date.now() + 30 * 60_000 });\n      console.log(`[mail] Reset link for ${user.email}: http://localhost:5173/reset-password?token=${token}`);\n    }\n    res.status(204).end();\n  });\n\n  app.post(\"/api/auth/reset-password\", (req, res) => {\n    const { token, password } = req.body as { token?: string; password?: string };\n    const grant = token ? resetTokens.get(token) : undefined;\n    const user = grant && grant.expiresAt > Date.now() ? findUserById(grant.userId) : undefined;\n    if (!user || !password || password.length < 10) {\n      res.status(400).json({ code: \"INVALID_TOKEN\", message: \"The link is invalid or has expired\" });\n      return;\n    }\n    resetTokens.delete(token!);\n    user.passwordHash = hashPassword(password);\n    for (const [t, g] of refreshTokens) if (g.userId === user.id) refreshTokens.delete(t); // sign out everywhere\n    res.status(204).end();\n  });\n\n  // Fake \"Sign in with Google\": a real app redirects to the provider with `state` + PKCE here.\n  app.get(\"/api/auth/google\", (_req, res) => {\n    const state = randomBytes(16).toString(\"base64url\");\n    res.cookie(\"oauth_state\", state, { httpOnly: true, sameSite: \"lax\", path: \"/api/auth\", maxAge: 5 * 60_000 });\n    res.redirect(`/api/auth/google/callback?code=demo-code&state=${state}`);\n  });\n\n  app.get(\"/api/auth/google/callback\", (req, res) => {\n    if (!req.query.state || req.query.state !== req.cookies?.oauth_state) {\n      res.redirect(\"/login?error=oauth_state\");\n      return;\n    }\n    res.clearCookie(\"oauth_state\", { path: \"/api/auth\" });\n    // Here the server exchanges `code` for the provider's tokens and reads the verified email.\n    const email = \"halina.demo@gmail.example\";\n    let user = usersByEmail.get(email);\n    if (!user) {\n      user = { id: randomUUID(), name: \"Halina (Google)\", email, passwordHash: null };\n      usersByEmail.set(email, user);\n    }\n    issueSession(res, user); // sets the refresh cookie – no tokens in the URL\n    res.redirect(\"/auth/callback\");\n  });\n\n  app.get(\"/api/me\", requireAuth, (_req, res) => {\n    const user = findUserById(String(res.locals.userId));\n    res.json(user ? publicUser(user) : null);\n  });\n\n  app.get(\"/api/orders\", requireAuth, (_req, res) => {\n    res.json([\n      { id: \"1042\", item: \"Ruskie × 20\", status: \"delivered\" },\n      { id: \"1057\", item: \"Z kaczką × 10\", status: \"cooking\" },\n    ]);\n  });\n\n  return app;\n}"}]}]}]},"toc":[{"id":"gdzie-trzymac-tokeny","text":"Gdzie trzymać tokeny","level":2,"locked":false},{"id":"krok-1-projekt-i-api-demonstracyjne","text":"Krok 1. Projekt i API demonstracyjne","level":2,"locked":false},{"id":"krok-2-klient-api-token-w-pamieci-i-retry-po-401","text":"Krok 2. Klient API: token w pamięci i retry po 401","level":2,"locked":true},{"id":"krok-3-authprovider-i-chronione-trasy","text":"Krok 3. AuthProvider i chronione trasy","level":2,"locked":true},{"id":"krok-4-formularze-logowania-i-rejestracji","text":"Krok 4. Formularze logowania i rejestracji","level":2,"locked":true},{"id":"krok-5-reset-hasla-i-powrot-z-logowania-spolecznosciowego","text":"Krok 5. Reset hasła i powrót z logowania społecznościowego","level":2,"locked":true},{"id":"krok-6-skladamy-aplikacje","text":"Krok 6. Składamy aplikację","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":49,"visibleBlocks":14,"resources":[{"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":"6b0857bd3c96f2d34d0b40c4","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/us/podcast/episode-99-shhh-its-a-secret-storing-api-keys/id467641329?i=1000701187746","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id467641329?i=1000701187746","title":"Episode 99. SHHH! It’s a secret! (Storing API Keys / Passwords / tokens!)","description":"Ok, so is time to talk about something secretive! Like API Passwords, Auth tokens, or keys... these are things that we want to have as a Secret within our microservice. And yeah, adding them into your source code is a big no-no Here we cover the dos...","author":"Java Pub House","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts221/v4/ca/24/a7/ca24a7a6-e926-cc14-223a-444cf4127b70/mza_6810655170352985611.png/600x600bb.jpg","durationSec":null,"lang":"en","topics":["microservices"],"techs":["java"],"tags":["podcast","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2022-01-02T05:19:57.000Z","popularity":40,"verifiedAt":"2026-11-26T11:04:06.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857b33c96f2d34d0b36b1","type":"repo","provider":"github","url":"https://github.com/yurisldk/realworld-react-fsd","embedUrl":null,"title":"yurisldk/realworld-react-fsd","description":"A real-world React application built with Feature-Sliced Design, evolving from a modular monolith toward a microfrontend-ready architecture.","author":"yurisldk","thumbnailUrl":"https://opengraph.githubassets.com/1/yurisldk/realworld-react-fsd","durationSec":null,"lang":"en","topics":["modular-monolith","monolith"],"techs":["typescript"],"tags":["feature-sliced","feature-sliced-design","jest","jwt-authentication","modular-monolith","modular-monolith-architecture","software-architecture","orval","react","react-query"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-05-27T20:46:51.000Z","popularity":53,"verifiedAt":"2026-11-26T10:58:41.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:51.220Z","updatedAt":"2026-11-26T16:00:51.220Z"},{"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"}],"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}]}}