English

Poradnik · Logowanie i rejestracja · React

Logowanie i rejestracja w React – formularze, tokeny, chronione trasy i odświeżanie sesji

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.

Autor · · 29 min czytania

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 npm run dev.

Wymagania wstępne: React z hookami, react-hook-form i TanStack Query (zob. poradnik React), podstawy HTTP (nagłówki, ciasteczka, kody statusu). Backend opisujemy tylko w zakresie potrzebnym frontendowi – szczegóły w temacie Uwierzytelnianie.

30 s
czas życia access tokena w demo – żeby zobaczyć odświeżanie na żywo
0
tokenów w localStorage – access w pamięci, refresh w ciasteczku httpOnly
1
wywołanie /refresh – nawet gdy 10 żądań dostanie 401 naraz
9
przepływów sprawdzonych w przeglądarce – od rejestracji po logowanie przez Google

Gdzie trzymać tokeny

MiejsceOdporność na XSSCSRFSesja po przeładowaniuOcena
localStorage / sessionStoragebrak – każdy skrypt odczyta tokenbrak ryzykatakwygodne, ale wyciek tokena przy pierwszym XSS
zwykłe ciasteczko (bez httpOnly)braktrzeba chronićtaknajgorsze z obu światów
access w pamięci + refresh w ciasteczku httpOnlyrefresh nieczytelny dla JS, access krótkiSameSite=Strict + ścieżka /api/authtak, przez /refreshdobry kompromis dla SPA – ten poradnik
sesja serwerowa / BFF (tylko ciasteczko httpOnly)token w ogóle nie trafia do przeglądarkitrzeba chronićtaknajbezpieczniejsze, wymaga backendu „dla frontendu”
Diagram: Logowanie, wygaśnięcie access tokena i ciche odświeżenie

Krok 1. Projekt i API demonstracyjne

npm create vite@latest pierogi-auth -- --template react-ts
cd pierogi-auth
npm install react-router @tanstack/react-query react-hook-form @hookform/resolvers zod
npm install -D express cookie-parser @types/express @types/cookie-parser @types/node

Aplikacja Express jest podpięta do serwera deweloperskiego Vite jako middleware (configureServer). 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.

Konfiguracja projektu

package.json
{
  "name": "pierogi-auth",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build"
  },
  "dependencies": {
    "@hookform/resolvers": "^7.0.9",
    "@tanstack/react-query": "^5.108.4",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "react-hook-form": "^7.92.0",
    "react-router": "^8.5.3",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/cookie-parser": "^1.4.10",
    "@types/express": "^5.0.6",
    "@types/node": "^24.0.0",
    "@types/react": "^19.3.0",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "cookie-parser": "^1.4.7",
    "express": "^5.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client", "node"],
    "jsx": "react-jsx",
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["src", "server", "vite.config.ts"]
}
vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { createAuthApi } from "./server/auth-api.ts";

// The demo API runs inside the Vite dev server (same origin = simple cookies, no CORS).
// In production the same Express app runs on its own behind your reverse proxy.
export default defineConfig({
  plugins: [
    react(),
    {
      name: "auth-api",
      configureServer(server) {
        server.middlewares.use(createAuthApi());
      },
    },
  ],
});
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogarnia · Account</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
src/index.css
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; color: #1f2328; background: #f6f7f9; }
a { color: #c2255c; }
.shell { max-width: 720px; margin: 0 auto; padding: 16px; }
.topbar { display: flex; gap: 16px; align-items: center; padding: 12px 0 16px; border-bottom: 1px solid #dee2e6; margin-bottom: 24px; }
.topbar .spacer { flex: 1; }
.card { background: #fff; border: 1px solid #dee2e6; border-radius: 12px; padding: 24px; max-width: 420px; margin: 0 auto; display: grid; gap: 14px; }
.field { display: grid; gap: 4px; }
.field input { padding: 9px 10px; border: 1px solid #ced4da; border-radius: 8px; font: inherit; }
.field input[aria-invalid="true"] { border-color: #c92a2a; }
.password { display: grid; grid-template-columns: 1fr auto; gap: 6px; }
.error { color: #c92a2a; font-size: 0.875rem; margin: 0; }
.notice { background: #ebfbee; border: 1px solid #b2f2bb; padding: 10px 12px; border-radius: 8px; margin: 0; }
.alert { background: #fff5f5; border: 1px solid #ffc9c9; padding: 10px 12px; border-radius: 8px; margin: 0; }
.muted { color: #6c757d; font-size: 0.875rem; }
button, .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; }
button.secondary, .button.secondary { background: #fff; color: #1f2328; border-color: #ced4da; }
button:disabled { opacity: 0.6; cursor: wait; }
.divider { display: flex; align-items: center; gap: 8px; color: #6c757d; font-size: 0.875rem; }
.divider::before, .divider::after { content: ""; flex: 1; border-top: 1px solid #dee2e6; }

API ma kształt produkcyjny, choć przechowuje dane w pamięci: hasła haszowane scrypt, access token w odpowiedzi JSON, refresh token w ciasteczku httpOnly + SameSite=Strict + path=/api/auth, rotacja refresh tokena przy każdym odświeżeniu i reset hasła, który wylogowuje ze wszystkich urządzeń.

Express: rejestracja, logowanie, refresh, reset hasła, OAuth

server/auth-api.ts
// A minimal, in-memory auth API for the tutorial. The flows and cookie flags are production-shaped;
// the storage (Maps) and the fake Google provider are not.
import cookieParser from "cookie-parser";
import express, { type NextFunction, type Request, type Response } from "express";
import { randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";

type User = { id: string; name: string; email: string; passwordHash: string | null };
type Grant = { userId: string; expiresAt: number };

const usersByEmail = new Map<string, User>();
const accessTokens = new Map<string, Grant>();
const refreshTokens = new Map<string, Grant>();
const resetTokens = new Map<string, Grant>();

const ACCESS_TTL_MS = 30_000; // deliberately short: watch the silent refresh in the Network tab
const REFRESH_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const REFRESH_COOKIE = "refresh_token";

function hashPassword(password: string): string {
  const salt = randomBytes(16);
  return `${salt.toString("hex")}:${scryptSync(password, salt, 32).toString("hex")}`;
}

function verifyPassword(password: string, stored: string | null): boolean {
  const [salt, hash] = (stored ?? "").split(":");
  if (!salt || !hash) return false;
  return timingSafeEqual(Buffer.from(hash, "hex"), scryptSync(password, Buffer.from(salt, "hex"), 32));
}

const publicUser = (u: User) => ({ id: u.id, name: u.name, email: u.email });
const findUserById = (id: string) => [...usersByEmail.values()].find((u) => u.id === id);

// Access token goes into the JSON body (kept in memory by the SPA);
// refresh token goes into an httpOnly cookie that JavaScript can't read.
function issueSession(res: Response, user: User) {
  const accessToken = randomUUID();
  accessTokens.set(accessToken, { userId: user.id, expiresAt: Date.now() + ACCESS_TTL_MS });
  const refreshToken = randomBytes(32).toString("base64url");
  refreshTokens.set(refreshToken, { userId: user.id, expiresAt: Date.now() + REFRESH_TTL_MS });
  res.cookie(REFRESH_COOKIE, refreshToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    path: "/api/auth", // the cookie is sent only to auth endpoints
    maxAge: REFRESH_TTL_MS,
  });
  return { accessToken, expiresIn: ACCESS_TTL_MS / 1000, user: publicUser(user) };
}

function requireAuth(req: Request, res: Response, next: NextFunction) {
  const token = req.headers.authorization?.replace(/^Bearer /, "");
  const grant = token ? accessTokens.get(token) : undefined;
  if (!grant || grant.expiresAt < Date.now()) {
    res.status(401).json({ code: grant ? "TOKEN_EXPIRED" : "UNAUTHORIZED", message: "Authentication required" });
    return;
  }
  res.locals.userId = grant.userId;
  next();
}

export function createAuthApi() {
  const app = express();
  app.use("/api", express.json(), cookieParser());

  app.post("/api/auth/register", (req, res) => {
    const { name, email, password } = req.body as { name?: string; email?: string; password?: string };
    if (!name || !email || !password || password.length < 10) {
      res.status(400).json({ code: "VALIDATION_FAILED", message: "Invalid data" });
      return;
    }
    const key = email.toLowerCase();
    if (usersByEmail.has(key)) {
      res.status(409).json({ code: "EMAIL_TAKEN", message: "An account with this email already exists" });
      return;
    }
    const user: User = { id: randomUUID(), name, email: key, passwordHash: hashPassword(password) };
    usersByEmail.set(key, user);
    res.status(201).json(issueSession(res, user));
  });

  app.post("/api/auth/login", (req, res) => {
    const { email, password } = req.body as { email?: string; password?: string };
    const user = usersByEmail.get((email ?? "").toLowerCase());
    // Same error for "no such user" and "wrong password" – no account enumeration.
    if (!user || !verifyPassword(password ?? "", user.passwordHash)) {
      res.status(401).json({ code: "INVALID_CREDENTIALS", message: "Wrong email or password" });
      return;
    }
    res.json(issueSession(res, user));
  });

  // Rotation: every refresh invalidates the old refresh token and sets a new cookie.
  app.post("/api/auth/refresh", (req, res) => {
    const token: string | undefined = req.cookies?.[REFRESH_COOKIE];
    const grant = token ? refreshTokens.get(token) : undefined;
    if (token) refreshTokens.delete(token);
    const user = grant && grant.expiresAt > Date.now() ? findUserById(grant.userId) : undefined;
    if (!user) {
      res.clearCookie(REFRESH_COOKIE, { path: "/api/auth" });
      res.status(401).json({ code: "NO_SESSION", message: "Please sign in" });
      return;
    }
    res.json(issueSession(res, user));
  });

  app.post("/api/auth/logout", (req, res) => {
    const token: string | undefined = req.cookies?.[REFRESH_COOKIE];
    if (token) refreshTokens.delete(token);
    res.clearCookie(REFRESH_COOKIE, { path: "/api/auth" });
    res.status(204).end();
  });

  // Always 204 – the response must not reveal whether the email has an account.
  app.post("/api/auth/forgot-password", (req, res) => {
    const user = usersByEmail.get(String(req.body?.email ?? "").toLowerCase());
    if (user) {
      const token = randomBytes(32).toString("base64url");
      resetTokens.set(token, { userId: user.id, expiresAt: Date.now() + 30 * 60_000 });
      console.log(`[mail] Reset link for ${user.email}: http://localhost:5173/reset-password?token=${token}`);
    }
    res.status(204).end();
  });

  app.post("/api/auth/reset-password", (req, res) => {
    const { token, password } = req.body as { token?: string; password?: string };
    const grant = token ? resetTokens.get(token) : undefined;
    const user = grant && grant.expiresAt > Date.now() ? findUserById(grant.userId) : undefined;
    if (!user || !password || password.length < 10) {
      res.status(400).json({ code: "INVALID_TOKEN", message: "The link is invalid or has expired" });
      return;
    }
    resetTokens.delete(token!);
    user.passwordHash = hashPassword(password);
    for (const [t, g] of refreshTokens) if (g.userId === user.id) refreshTokens.delete(t); // sign out everywhere
    res.status(204).end();
  });

  // Fake "Sign in with Google": a real app redirects to the provider with `state` + PKCE here.
  app.get("/api/auth/google", (_req, res) => {
    const state = randomBytes(16).toString("base64url");
    res.cookie("oauth_state", state, { httpOnly: true, sameSite: "lax", path: "/api/auth", maxAge: 5 * 60_000 });
    res.redirect(`/api/auth/google/callback?code=demo-code&state=${state}`);
  });

  app.get("/api/auth/google/callback", (req, res) => {
    if (!req.query.state || req.query.state !== req.cookies?.oauth_state) {
      res.redirect("/login?error=oauth_state");
      return;
    }
    res.clearCookie("oauth_state", { path: "/api/auth" });
    // Here the server exchanges `code` for the provider's tokens and reads the verified email.
    const email = "halina.demo@gmail.example";
    let user = usersByEmail.get(email);
    if (!user) {
      user = { id: randomUUID(), name: "Halina (Google)", email, passwordHash: null };
      usersByEmail.set(email, user);
    }
    issueSession(res, user); // sets the refresh cookie – no tokens in the URL
    res.redirect("/auth/callback");
  });

  app.get("/api/me", requireAuth, (_req, res) => {
    const user = findUserById(String(res.locals.userId));
    res.json(user ? publicUser(user) : null);
  });

  app.get("/api/orders", requireAuth, (_req, res) => {
    res.json([
      { id: "1042", item: "Ruskie × 20", status: "delivered" },
      { id: "1057", item: "Z kaczką × 10", status: "cooking" },
    ]);
  });

  return app;
}

Dalsza część artykułu dla zalogowanych

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

  • Krok 2. Klient API: token w pamięci i retry po 401
  • Krok 3. AuthProvider i chronione trasy
  • Krok 4. Formularze logowania i rejestracji
  • Krok 5. Reset hasła i powrót z logowania społecznościowego
  • Krok 6. Składamy aplikację
  • Typowe błędy
  • Sprawdź się
  • Co dalej

Załóż darmowe konto · Zaloguj się