English

Poradnik · NestJS · Logowanie i rejestracja

Autoryzacja w NestJS 12 – guardy, role i uprawnienia z CASL, JWT z odświeżaniem i wielodostępność (multi-tenant)

Uwierzytelnienie mówi, kim jesteś, autoryzacja – co wolno Ci zrobić z tym konkretnym zasobem. Budujemy API platformy SaaS dla sieci pierogarni: globalny guard JWT, role zamienione w reguły CASL z warunkami (lokal, kurier, status) i uprawnieniami do pól, polityki na trasach, natychmiastowe odebranie uprawnień po zmianie roli, rotacja refresh tokenów i izolacja najemców – z prawdziwymi odpowiedziami HTTP.

Autor · · 19 min czytania

Większość wycieków danych w API to nie złamane hasła, tylko brak sprawdzenia uprawnień do konkretnego obiektu: zalogowany użytkownik zmienia id w adresie i widzi cudze zamówienie (OWASP API Security nazywa to BOLA – Broken Object Level Authorization – i od lat stawia na pierwszym miejscu listy). Sam guard z listą ról tego nie załatwi, bo rola „kucharz” nie mówi, w którym lokalu i przy jakim statusie zamówienia wolno coś zmienić. W tym poradniku zbudujesz autoryzację warstwami – od tokenu, przez politykę na trasie, po regułę na poziomie obiektu i pola – i sprawdzisz każdą warstwę prawdziwym żądaniem.

Wymagania wstępne: Uwierzytelnianie: JWT, sesje i OAuth (hasła, ciasteczka, rotacja tokenów – tu tylko przypominamy), NestJS w praktyce, Node.js 24 LTS.

4
warstwy kontroli – token, polityka trasy, obiekt, pole
401 / 403 / 404
trzy różne odpowiedzi – kto jesteś, co wolno, czy w ogóle istnieje
15 min
życie access tokenu – refresh token rotowany przy każdym użyciu
1
miejsce na reguły – `AbilityFactory` z CASL

Droga żądania przez warstwy autoryzacji

Diagram: Kolejne bramki w NestJS – każda odpowiada innym kodem

RBAC, ABAC i polityki – słownik

ModelPytaniePrzykładGdzie w kodzie
RBAC (role)„Jaką masz rolę?”tylko właściciel zarządza rolamirole w tokenie, @CheckPolicies
ABAC (atrybuty)„Jakie cechy mają użytkownik i zasób?”kucharz – zamówienia swojego lokalu w statusie „w kuchni”warunki w regułach CASL
Uprawnienia do pól„Które pola możesz zmienić?”kucharz zmienia status, nie totalCentslista pól w regule CASL
ReBAC (relacje)„Jaki masz związek z zasobem?”kurier przypisany do zamówieniawarunek courierId: user.sub (przy złożonych grafach: OpenFGA, SpiceDB)

Krok 1. Projekt i moduł

Konfiguracja, start i moduł aplikacji

package.json
{
  "name": "pierogi-saas-rbac",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "engines": { "node": ">=24" },
  "scripts": {
    "build": "tsc -p tsconfig.json",
    "start": "node --env-file-if-exists=.env dist/main.js"
  },
  "dependencies": {
    "@casl/ability": "^7.1.3",
    "@nestjs/common": "^12.6.3",
    "@nestjs/core": "^12.6.3",
    "@nestjs/jwt": "^12.0.5",
    "@nestjs/platform-express": "^12.6.3",
    "reflect-metadata": "^0.2.2",
    "rxjs": "^7.8.2",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/express": "^5.0.6",
    "@types/node": "^24.19.4",
    "typescript": "~6.0.3"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "types": ["node"],
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "sourceMap": true
  },
  "include": ["src"]
}
src/main.ts
import "reflect-metadata";
import { StandardSchemaValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module.js";

const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new StandardSchemaValidationPipe());
app.enableShutdownHooks();
await app.listen(Number(process.env.PORT ?? 3000));
src/app.module.ts
import { Module } from "@nestjs/common";
import { APP_FILTER, APP_GUARD } from "@nestjs/core";
import { JwtModule } from "@nestjs/jwt";
import { AuthController } from "./auth/auth.controller.js";
import { JwtAuthGuard } from "./auth/jwt-auth.guard.js";
import { TokenService } from "./auth/token.service.js";
import { AbilityFactory } from "./authz/ability.factory.js";
import { CaslForbiddenFilter } from "./authz/forbidden.filter.js";
import { PoliciesGuard } from "./authz/policies.js";
import { OrdersController } from "./orders/orders.controller.js";
import { OrdersService } from "./orders/orders.service.js";

function jwtSecret(): string {
  const secret = process.env.JWT_SECRET;
  if (!secret || secret.length < 32) throw new Error("JWT_SECRET (at least 32 characters) is required");
  return secret;
}

@Module({
  imports: [
    JwtModule.registerAsync({
      useFactory: () => ({
        secret: jwtSecret(),
        signOptions: { expiresIn: "15m", issuer: "pierogi-saas", audience: "pierogi-api", algorithm: "HS256" },
        verifyOptions: { issuer: "pierogi-saas", audience: "pierogi-api", algorithms: ["HS256"] },
      }),
    }),
  ],
  controllers: [AuthController, OrdersController],
  providers: [
    TokenService,
    AbilityFactory,
    PoliciesGuard,
    OrdersService,
    { provide: APP_GUARD, useClass: JwtAuthGuard }, // authentication for every route
    { provide: APP_FILTER, useClass: CaslForbiddenFilter },
  ],
})
export class AppModule {}
  • JwtAuthGuard jako APP_GUARD – każda trasa wymaga tokenu, chyba że oznaczysz ją @Public(). Bezpieczna wartość domyślna: zapomniany dekorator oznacza „zamknięte”, a nie „otwarte”.
  • verifyOptions z algorithms: ["HS256"], issuer i audience – token wystawiony dla innej usługi albo podpisany innym algorytmem zostanie odrzucony. Sekret ma co najmniej 32 znaki i przychodzi ze zmiennej środowiskowej; aplikacja bez niego nie wystartuje.
  • StandardSchemaValidationPipe (Nest 12) waliduje ciała żądań schematami Zod; .strict() w schemacie aktualizacji zamienia nieznane pola w błąd 400.

Krok 2. Co jest w tokenie

Claims, dekoratory i dane demonstracyjne

src/auth/claims.ts
import { createParamDecorator, SetMetadata, type ExecutionContext } from "@nestjs/common";
import type { Request } from "express";
import type { Role } from "../data.js";

// What we put in the access token: identity + tenant + role + a permission version.
// No e-mail, no names – the token is readable by anyone who has it.
export type Claims = { sub: string; tid: string; role: Role; loc: string | null; pv: number };

export type AuthedRequest = Request & { user: Claims };

export const IS_PUBLIC = "auth:public";
export const Public = () => SetMetadata(IS_PUBLIC, true);

export const CurrentUser = createParamDecorator((_: unknown, ctx: ExecutionContext) => ctx.switchToHttp().getRequest<AuthedRequest>().user);
src/data.ts
// In-memory "database" of a multi-tenant SaaS for dumpling restaurants.
// Two tenants (restaurant chains), each with locations, users and orders.
export type Role = "owner" | "manager" | "cook" | "courier";
export type OrderStatus = "placed" | "cooking" | "ready" | "delivered";

export type User = { id: string; tenantId: string; role: Role; locationId: string | null; permVersion: number };
export type Order = { id: string; tenantId: string; locationId: string; courierId: string | null; status: OrderStatus; totalCents: number };

export const users: User[] = [
  { id: "u-ola", tenantId: "t-pierogi", role: "owner", locationId: null, permVersion: 1 },
  { id: "u-marek", tenantId: "t-pierogi", role: "manager", locationId: "loc-krakow", permVersion: 1 },
  { id: "u-ewa", tenantId: "t-pierogi", role: "cook", locationId: "loc-krakow", permVersion: 1 },
  { id: "u-jan", tenantId: "t-pierogi", role: "courier", locationId: "loc-krakow", permVersion: 1 },
  { id: "u-tom", tenantId: "t-babcia", role: "owner", locationId: null, permVersion: 1 },
];

export const orders: Order[] = [
  { id: "o-1001", tenantId: "t-pierogi", locationId: "loc-krakow", courierId: "u-jan", status: "placed", totalCents: 7500 },
  { id: "o-1002", tenantId: "t-pierogi", locationId: "loc-gdansk", courierId: null, status: "cooking", totalCents: 5200 },
  { id: "o-2001", tenantId: "t-babcia", locationId: "loc-poznan", courierId: null, status: "placed", totalCents: 3100 },
];

Token zawiera tylko to, czego potrzebuje autoryzacja: sub (użytkownik), tid (najemca), role, loc (lokal) i pv – wersję uprawnień. Żadnych e-maili ani imion: JWT jest podpisany, nie zaszyfrowany, więc każdy, kto go ma, odczyta zawartość.

Odpowiedź POST /auth/login (skrócona) i zdekodowany payload access tokenu
{ "accessToken": "eyJhbGciOiJI…", "refreshToken": "6b5x6OSq-YFe…", "expiresIn": 900 }

{"sub":"u-ewa","tid":"t-pierogi","role":"cook","loc":"loc-krakow","pv":1,"iat":1795791961,"exp":1795792861,"aud":"pierogi-api","iss":"pierogi-saas"}

Krok 3. Guard JWT, rotacja i natychmiastowe odebranie uprawnień

Guard, serwis tokenów i kontroler auth

src/auth/jwt-auth.guard.ts
import { Injectable, UnauthorizedException, type CanActivate, type ExecutionContext } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { JwtService } from "@nestjs/jwt";
import { users } from "../data.js";
import { IS_PUBLIC, type AuthedRequest, type Claims } from "./claims.js";

// Global guard: every route requires a valid access token unless marked @Public().
@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
    private readonly jwt: JwtService,
    private readonly reflector: Reflector,
  ) {}

  async canActivate(ctx: ExecutionContext): Promise<boolean> {
    if (this.reflector.getAllAndOverride<boolean>(IS_PUBLIC, [ctx.getHandler(), ctx.getClass()])) return true;
    const req = ctx.switchToHttp().getRequest<AuthedRequest>();
    const [scheme, token] = (req.headers.authorization ?? "").split(" ");
    if (scheme !== "Bearer" || !token) throw new UnauthorizedException("Missing bearer token");

    let claims: Claims;
    try {
      // algorithms, issuer and audience come from JwtModule verifyOptions
      claims = await this.jwt.verifyAsync<Claims>(token);
    } catch {
      throw new UnauthorizedException("Invalid or expired token");
    }

    // Role changed or user blocked since the token was issued? Then the token is outdated.
    // A cheap lookup (cache it in Redis/memory) buys immediate revocation of permissions.
    const user = users.find((u) => u.id === claims.sub);
    if (!user || user.permVersion !== claims.pv) throw new UnauthorizedException("Token outdated – refresh it");

    req.user = claims;
    return true;
  }
}
src/auth/token.service.ts
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { users, type User } from "../data.js";
import type { Claims } from "./claims.js";

type RefreshRecord = { userId: string; familyId: string; used: boolean; expiresAt: number };
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");

@Injectable()
export class TokenService {
  // Store only hashes of refresh tokens (here in memory; in production: Redis or a table).
  private readonly refresh = new Map<string, RefreshRecord>();

  constructor(private readonly jwt: JwtService) {}

  async issue(user: User, familyId: string = randomUUID()) {
    const claims: Claims = { sub: user.id, tid: user.tenantId, role: user.role, loc: user.locationId, pv: user.permVersion };
    const accessToken = await this.jwt.signAsync(claims); // 15 min, see JwtModule options
    const refreshToken = randomBytes(32).toString("base64url");
    this.refresh.set(sha256(refreshToken), { userId: user.id, familyId, used: false, expiresAt: Date.now() + 7 * 24 * 3600_000 });
    return { accessToken, refreshToken, expiresIn: 900 };
  }

  // Rotation with reuse detection: an already used refresh token revokes the whole family.
  async rotate(refreshToken: string) {
    const record = this.refresh.get(sha256(refreshToken));
    if (!record || record.expiresAt < Date.now()) throw new UnauthorizedException("Invalid refresh token");
    if (record.used) {
      for (const [hash, r] of this.refresh) if (r.familyId === record.familyId) this.refresh.delete(hash);
      throw new UnauthorizedException("Refresh token reuse detected – please sign in again");
    }
    record.used = true;
    const user = users.find((u) => u.id === record.userId);
    if (!user) throw new UnauthorizedException("User no longer exists");
    return this.issue(user, record.familyId); // the new token carries the CURRENT role and permVersion
  }
}
src/auth/auth.controller.ts
import { Body, Controller, ForbiddenException, HttpCode, NotFoundException, Param, Patch, Post, UnauthorizedException } from "@nestjs/common";
import { z } from "zod";
import { users } from "../data.js";
import { CurrentUser, Public, type Claims } from "./claims.js";
import { TokenService } from "./token.service.js";

@Controller()
export class AuthController {
  constructor(private readonly tokens: TokenService) {}

  // DEMO ONLY: signs in by user id. Real password/OAuth sign-in: see the authentication tutorial.
  @Public()
  @Post("auth/login")
  @HttpCode(200)
  login(@Body({ schema: z.object({ userId: z.string() }) }) body: { userId: string }) {
    const user = users.find((u) => u.id === body.userId);
    if (!user) throw new UnauthorizedException("Unknown user");
    return this.tokens.issue(user);
  }

  @Public()
  @Post("auth/refresh")
  @HttpCode(200)
  refresh(@Body({ schema: z.object({ refreshToken: z.string().min(20) }) }) body: { refreshToken: string }) {
    return this.tokens.rotate(body.refreshToken);
  }

  // Changing a role bumps permVersion → all existing access tokens of that user stop working.
  @Patch("users/:id/role")
  changeRole(@CurrentUser() me: Claims, @Param("id") id: string, @Body({ schema: z.object({ role: z.enum(["manager", "cook", "courier"]) }) }) body: { role: "manager" | "cook" | "courier" }) {
    if (me.role !== "owner") throw new ForbiddenException("Only the owner manages roles");
    const user = users.find((u) => u.id === id && u.tenantId === me.tid);
    if (!user) throw new NotFoundException(`User ${id} not found`);
    user.role = body.role;
    user.permVersion += 1;
    return { id: user.id, role: user.role, permVersion: user.permVersion };
  }
}

Dalsza część artykułu dla zalogowanych

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

  • Krok 4. Uprawnienia w jednym miejscu: CASL
  • Krok 5. Obiekt, pole i reguła biznesowa w serwisie
  • Wielodostępność (multi-tenant): na co uważać
  • Typowe błędy
  • Sprawdź się
  • Co dalej

Załóż darmowe konto · Zaloguj się