{"id":"6b09aa805a5e2dbc3f20a48f","slug":"nestjs-auth-rbac","title":"Autoryzacja w NestJS 12 – guardy, role i uprawnienia z CASL, JWT z odświeżaniem i wielodostępność (multi-tenant)","summary":"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.","servedLang":"pl","availableLangs":["pl","en"],"topics":["nestjs","authentication","api-security"],"techs":["node","typescript"],"tags":["nestjs-12","authorization","rbac","abac","casl","jwt","refresh-token-rotation","multi-tenant","row-level-security","bola","guards"],"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":19,"stats":{"views":1,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T16:06:24.765Z","updatedAt":"2026-11-27T16:08:50.676Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"tint","weaveResources":true,"toc":"right"},"seoDescription":"Autoryzacja NestJS 12 krok po kroku – APP_GUARD z JWT, RBAC vs ABAC, CASL 7 (AbilityBuilder, createMongoAbility, subject, ForbiddenError, uprawnienia do pól), @CheckPolicies, 401 vs 403 vs 404, wersja uprawnień w tokenie, rotacja refresh tokenów, multi-tenant i Row Level Security w PostgreSQL.","wordCount":3711,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Większość wycieków danych w API to nie złamane hasła, tylko "},{"type":"text","text":"brak sprawdzenia uprawnień do konkretnego obiektu","marks":[{"type":"bold"}]},{"type":"text","text":": zalogowany użytkownik zmienia "},{"type":"text","text":"id","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Uwierzytelnienie (401) ≠ autoryzacja (403).","marks":[{"type":"bold"}]},{"type":"text","text":" Globalny guard JWT sprawdza podpis, ważność, wydawcę i odbiorcę tokenu. O tym, co wolno, decydują reguły – najlepiej w jednym miejscu (CASL), a nie w "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":"-ach rozsianych po kontrolerach."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Role to paczki uprawnień, a warunki robią z nich ABAC.","marks":[{"type":"bold"}]},{"type":"text","text":" „Kucharz może zmienić "},{"type":"text","text":"tylko status","marks":[{"type":"italic"}]},{"type":"text","text":" zamówień "},{"type":"text","text":"swojego lokalu","marks":[{"type":"italic"}]},{"type":"text","text":", "},{"type":"text","text":"dopóki są w kuchni","marks":[{"type":"italic"}]},{"type":"text","text":"” – to jedna reguła CASL z polami i warunkami."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Najemca (tenant) pochodzi z tokenu, nigdy z żądania.","marks":[{"type":"bold"}]},{"type":"text","text":" Cudze dane odpowiadają 404, a nie 403. Zmiana roli podbija wersję uprawnień, więc stare tokeny przestają działać od razu."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"API platformy SaaS w NestJS 12 (ESM) dla sieci pierogarni: dwóch najemców, role właściciel / menedżer / kucharz / kurier, logowanie z access tokenem (15 min) i rotowanym refresh tokenem, globalny "},{"type":"text","text":"JwtAuthGuard","marks":[{"type":"code"}]},{"type":"text","text":", fabryka uprawnień CASL, dekorator "},{"type":"text","text":"@CheckPolicies","marks":[{"type":"code"}]},{"type":"text","text":", kontrola na poziomie obiektu i pól w serwisie, filtr zamieniający błąd CASL na 403 i zmiana roli unieważniająca stare tokeny. Do tego przykład Row Level Security w PostgreSQL. Kod pobierzesz jako ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"Uwierzytelnianie: JWT, sesje i OAuth","marks":[{"type":"link","attrs":{"href":"/pl/articles/authentication"}}]},{"type":"text","text":" (hasła, ciasteczka, rotacja tokenów – tu tylko przypominamy), "},{"type":"text","text":"NestJS w praktyce","marks":[{"type":"link","attrs":{"href":"/pl/articles/nestjs"}}]},{"type":"text","text":", Node.js 24 LTS."}]},{"type":"stats","attrs":{"items":[{"value":"4","label":"warstwy kontroli","hint":"token, polityka trasy, obiekt, pole"},{"value":"401 / 403 / 404","label":"trzy różne odpowiedzi","hint":"kto jesteś, co wolno, czy w ogóle istnieje"},{"value":"15 min","label":"życie access tokenu","hint":"refresh token rotowany przy każdym użyciu"},{"value":"1","label":"miejsce na reguły","hint":"`AbilityFactory` z CASL"}]}},{"type":"heading","attrs":{"level":2,"id":"droga-zadania-przez-warstwy-autoryzacji"},"content":[{"type":"text","text":"Droga żądania przez warstwy autoryzacji"}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  R[\"PATCH /orders/o-1001<br/>Authorization: Bearer …\"] --> G1{\"JwtAuthGuard<br/>podpis, exp, iss, aud,<br/>wersja uprawnień\"}\n  G1 -->|\"nie\"| E401[\"401 Unauthorized\"]\n  G1 -->|\"tak\"| G2{\"PoliciesGuard<br/>czy ta rola w ogóle<br/>ma dostęp do zasobu?\"}\n  G2 -->|\"nie\"| E403a[\"403 Forbidden\"]\n  G2 -->|\"tak\"| P[\"Pipe: schemat Zod<br/>(nieznane pola = 400)\"]\n  P --> S1{\"Serwis: zamówienie<br/>w moim najemcy?\"}\n  S1 -->|\"nie\"| E404[\"404 Not Found\"]\n  S1 -->|\"tak\"| S2{\"CASL: obiekt i pola<br/>lokal, kurier, status\"}\n  S2 -->|\"nie\"| E403b[\"403 Forbidden\"]\n  S2 -->|\"tak\"| S3{\"Reguły biznesowe<br/>dozwolone przejście statusu?\"}\n  S3 -->|\"nie\"| E400[\"400 Bad Request\"]\n  S3 -->|\"tak\"| OK[\"200 OK\"]","caption":"Kolejne bramki w NestJS – każda odpowiada innym kodem"}},{"type":"heading","attrs":{"level":2,"id":"rbac-abac-i-polityki-slownik"},"content":[{"type":"text","text":"RBAC, ABAC i polityki – słownik"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Model"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Pytanie"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przykład"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Gdzie w kodzie"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"RBAC (role)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"„Jaką masz rolę?”"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tylko właściciel zarządza rolami"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"role","marks":[{"type":"code"}]},{"type":"text","text":" w tokenie, "},{"type":"text","text":"@CheckPolicies","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ABAC (atrybuty)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"„Jakie cechy mają użytkownik i zasób?”"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"kucharz – zamówienia swojego lokalu w statusie „w kuchni”"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"warunki w regułach CASL"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Uprawnienia do pól"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"„Które pola możesz zmienić?”"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"kucharz zmienia "},{"type":"text","text":"status","marks":[{"type":"code"}]},{"type":"text","text":", nie "},{"type":"text","text":"totalCents","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"lista pól w regule CASL"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ReBAC (relacje)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"„Jaki masz związek z zasobem?”"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"kurier przypisany do zamówienia"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"warunek "},{"type":"text","text":"courierId: user.sub","marks":[{"type":"code"}]},{"type":"text","text":" (przy złożonych grafach: OpenFGA, SpiceDB)"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-1-projekt-i-modul"},"content":[{"type":"text","text":"Krok 1. Projekt i moduł"}]},{"type":"codeGroup","attrs":{"title":"Konfiguracja, start i moduł aplikacji"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-saas-rbac\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"type\": \"module\",\n  \"engines\": { \"node\": \">=24\" },\n  \"scripts\": {\n    \"build\": \"tsc -p tsconfig.json\",\n    \"start\": \"node --env-file-if-exists=.env dist/main.js\"\n  },\n  \"dependencies\": {\n    \"@casl/ability\": \"^7.1.3\",\n    \"@nestjs/common\": \"^12.6.3\",\n    \"@nestjs/core\": \"^12.6.3\",\n    \"@nestjs/jwt\": \"^12.0.5\",\n    \"@nestjs/platform-express\": \"^12.6.3\",\n    \"reflect-metadata\": \"^0.2.2\",\n    \"rxjs\": \"^7.8.2\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^5.0.6\",\n    \"@types/node\": \"^24.19.4\",\n    \"typescript\": \"~6.0.3\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"es2023\",\n    \"module\": \"nodenext\",\n    \"moduleResolution\": \"nodenext\",\n    \"types\": [\"node\"],\n    \"outDir\": \"dist\",\n    \"rootDir\": \"src\",\n    \"strict\": true,\n    \"experimentalDecorators\": true,\n    \"emitDecoratorMetadata\": true,\n    \"skipLibCheck\": true,\n    \"sourceMap\": true\n  },\n  \"include\": [\"src\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/main.ts"},"content":[{"type":"text","text":"import \"reflect-metadata\";\nimport { StandardSchemaValidationPipe } from \"@nestjs/common\";\nimport { NestFactory } from \"@nestjs/core\";\nimport { AppModule } from \"./app.module.js\";\n\nconst app = await NestFactory.create(AppModule);\napp.useGlobalPipes(new StandardSchemaValidationPipe());\napp.enableShutdownHooks();\nawait app.listen(Number(process.env.PORT ?? 3000));"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/app.module.ts"},"content":[{"type":"text","text":"import { Module } from \"@nestjs/common\";\nimport { APP_FILTER, APP_GUARD } from \"@nestjs/core\";\nimport { JwtModule } from \"@nestjs/jwt\";\nimport { AuthController } from \"./auth/auth.controller.js\";\nimport { JwtAuthGuard } from \"./auth/jwt-auth.guard.js\";\nimport { TokenService } from \"./auth/token.service.js\";\nimport { AbilityFactory } from \"./authz/ability.factory.js\";\nimport { CaslForbiddenFilter } from \"./authz/forbidden.filter.js\";\nimport { PoliciesGuard } from \"./authz/policies.js\";\nimport { OrdersController } from \"./orders/orders.controller.js\";\nimport { OrdersService } from \"./orders/orders.service.js\";\n\nfunction jwtSecret(): string {\n  const secret = process.env.JWT_SECRET;\n  if (!secret || secret.length < 32) throw new Error(\"JWT_SECRET (at least 32 characters) is required\");\n  return secret;\n}\n\n@Module({\n  imports: [\n    JwtModule.registerAsync({\n      useFactory: () => ({\n        secret: jwtSecret(),\n        signOptions: { expiresIn: \"15m\", issuer: \"pierogi-saas\", audience: \"pierogi-api\", algorithm: \"HS256\" },\n        verifyOptions: { issuer: \"pierogi-saas\", audience: \"pierogi-api\", algorithms: [\"HS256\"] },\n      }),\n    }),\n  ],\n  controllers: [AuthController, OrdersController],\n  providers: [\n    TokenService,\n    AbilityFactory,\n    PoliciesGuard,\n    OrdersService,\n    { provide: APP_GUARD, useClass: JwtAuthGuard }, // authentication for every route\n    { provide: APP_FILTER, useClass: CaslForbiddenFilter },\n  ],\n})\nexport class AppModule {}"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"JwtAuthGuard","marks":[{"type":"code"}]},{"type":"text","text":" jako ","marks":[{"type":"bold"}]},{"type":"text","text":"APP_GUARD","marks":[{"type":"code"}]},{"type":"text","text":" – każda trasa wymaga tokenu, chyba że oznaczysz ją "},{"type":"text","text":"@Public()","marks":[{"type":"code"}]},{"type":"text","text":". Bezpieczna wartość domyślna: zapomniany dekorator oznacza „zamknięte”, a nie „otwarte”."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"verifyOptions","marks":[{"type":"code"}]},{"type":"text","text":" z ","marks":[{"type":"bold"}]},{"type":"text","text":"algorithms: [\"HS256\"]","marks":[{"type":"code"}]},{"type":"text","text":", ","marks":[{"type":"bold"}]},{"type":"text","text":"issuer","marks":[{"type":"code"}]},{"type":"text","text":" i ","marks":[{"type":"bold"}]},{"type":"text","text":"audience","marks":[{"type":"code"}]},{"type":"text","text":" – 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."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"StandardSchemaValidationPipe","marks":[{"type":"code"}]},{"type":"text","text":" (Nest 12) waliduje ciała żądań schematami Zod; "},{"type":"text","text":".strict()","marks":[{"type":"code"}]},{"type":"text","text":" w schemacie aktualizacji zamienia nieznane pola w błąd 400."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-2-co-jest-w-tokenie"},"content":[{"type":"text","text":"Krok 2. Co jest w tokenie"}]},{"type":"codeGroup","attrs":{"title":"Claims, dekoratory i dane demonstracyjne"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/claims.ts"},"content":[{"type":"text","text":"import { createParamDecorator, SetMetadata, type ExecutionContext } from \"@nestjs/common\";\nimport type { Request } from \"express\";\nimport type { Role } from \"../data.js\";\n\n// What we put in the access token: identity + tenant + role + a permission version.\n// No e-mail, no names – the token is readable by anyone who has it.\nexport type Claims = { sub: string; tid: string; role: Role; loc: string | null; pv: number };\n\nexport type AuthedRequest = Request & { user: Claims };\n\nexport const IS_PUBLIC = \"auth:public\";\nexport const Public = () => SetMetadata(IS_PUBLIC, true);\n\nexport const CurrentUser = createParamDecorator((_: unknown, ctx: ExecutionContext) => ctx.switchToHttp().getRequest<AuthedRequest>().user);"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/data.ts"},"content":[{"type":"text","text":"// In-memory \"database\" of a multi-tenant SaaS for dumpling restaurants.\n// Two tenants (restaurant chains), each with locations, users and orders.\nexport type Role = \"owner\" | \"manager\" | \"cook\" | \"courier\";\nexport type OrderStatus = \"placed\" | \"cooking\" | \"ready\" | \"delivered\";\n\nexport type User = { id: string; tenantId: string; role: Role; locationId: string | null; permVersion: number };\nexport type Order = { id: string; tenantId: string; locationId: string; courierId: string | null; status: OrderStatus; totalCents: number };\n\nexport const users: User[] = [\n  { id: \"u-ola\", tenantId: \"t-pierogi\", role: \"owner\", locationId: null, permVersion: 1 },\n  { id: \"u-marek\", tenantId: \"t-pierogi\", role: \"manager\", locationId: \"loc-krakow\", permVersion: 1 },\n  { id: \"u-ewa\", tenantId: \"t-pierogi\", role: \"cook\", locationId: \"loc-krakow\", permVersion: 1 },\n  { id: \"u-jan\", tenantId: \"t-pierogi\", role: \"courier\", locationId: \"loc-krakow\", permVersion: 1 },\n  { id: \"u-tom\", tenantId: \"t-babcia\", role: \"owner\", locationId: null, permVersion: 1 },\n];\n\nexport const orders: Order[] = [\n  { id: \"o-1001\", tenantId: \"t-pierogi\", locationId: \"loc-krakow\", courierId: \"u-jan\", status: \"placed\", totalCents: 7500 },\n  { id: \"o-1002\", tenantId: \"t-pierogi\", locationId: \"loc-gdansk\", courierId: null, status: \"cooking\", totalCents: 5200 },\n  { id: \"o-2001\", tenantId: \"t-babcia\", locationId: \"loc-poznan\", courierId: null, status: \"placed\", totalCents: 3100 },\n];"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Token zawiera tylko to, czego potrzebuje autoryzacja: "},{"type":"text","text":"sub","marks":[{"type":"code"}]},{"type":"text","text":" (użytkownik), "},{"type":"text","text":"tid","marks":[{"type":"code"}]},{"type":"text","text":" (najemca), "},{"type":"text","text":"role","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"loc","marks":[{"type":"code"}]},{"type":"text","text":" (lokal) i "},{"type":"text","text":"pv","marks":[{"type":"code"}]},{"type":"text","text":" – "},{"type":"text","text":"wersję uprawnień","marks":[{"type":"bold"}]},{"type":"text","text":". Żadnych e-maili ani imion: JWT jest podpisany, nie zaszyfrowany, więc każdy, kto go ma, odczyta zawartość."}]},{"type":"output","attrs":{"title":"Odpowiedź POST /auth/login (skrócona) i zdekodowany payload access tokenu","language":"json","content":"{ \"accessToken\": \"eyJhbGciOiJI…\", \"refreshToken\": \"6b5x6OSq-YFe…\", \"expiresIn\": 900 }\n\n{\"sub\":\"u-ewa\",\"tid\":\"t-pierogi\",\"role\":\"cook\",\"loc\":\"loc-krakow\",\"pv\":1,\"iat\":1795791961,\"exp\":1795792861,\"aud\":\"pierogi-api\",\"iss\":\"pierogi-saas\"}"}},{"type":"heading","attrs":{"level":2,"id":"krok-3-guard-jwt-rotacja-i-natychmiastowe-odebranie-uprawnien"},"content":[{"type":"text","text":"Krok 3. Guard JWT, rotacja i natychmiastowe odebranie uprawnień"}]},{"type":"codeGroup","attrs":{"title":"Guard, serwis tokenów i kontroler auth"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/jwt-auth.guard.ts"},"content":[{"type":"text","text":"import { Injectable, UnauthorizedException, type CanActivate, type ExecutionContext } from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\nimport { JwtService } from \"@nestjs/jwt\";\nimport { users } from \"../data.js\";\nimport { IS_PUBLIC, type AuthedRequest, type Claims } from \"./claims.js\";\n\n// Global guard: every route requires a valid access token unless marked @Public().\n@Injectable()\nexport class JwtAuthGuard implements CanActivate {\n  constructor(\n    private readonly jwt: JwtService,\n    private readonly reflector: Reflector,\n  ) {}\n\n  async canActivate(ctx: ExecutionContext): Promise<boolean> {\n    if (this.reflector.getAllAndOverride<boolean>(IS_PUBLIC, [ctx.getHandler(), ctx.getClass()])) return true;\n    const req = ctx.switchToHttp().getRequest<AuthedRequest>();\n    const [scheme, token] = (req.headers.authorization ?? \"\").split(\" \");\n    if (scheme !== \"Bearer\" || !token) throw new UnauthorizedException(\"Missing bearer token\");\n\n    let claims: Claims;\n    try {\n      // algorithms, issuer and audience come from JwtModule verifyOptions\n      claims = await this.jwt.verifyAsync<Claims>(token);\n    } catch {\n      throw new UnauthorizedException(\"Invalid or expired token\");\n    }\n\n    // Role changed or user blocked since the token was issued? Then the token is outdated.\n    // A cheap lookup (cache it in Redis/memory) buys immediate revocation of permissions.\n    const user = users.find((u) => u.id === claims.sub);\n    if (!user || user.permVersion !== claims.pv) throw new UnauthorizedException(\"Token outdated – refresh it\");\n\n    req.user = claims;\n    return true;\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/token.service.ts"},"content":[{"type":"text","text":"import { Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { JwtService } from \"@nestjs/jwt\";\nimport { createHash, randomBytes, randomUUID } from \"node:crypto\";\nimport { users, type User } from \"../data.js\";\nimport type { Claims } from \"./claims.js\";\n\ntype RefreshRecord = { userId: string; familyId: string; used: boolean; expiresAt: number };\nconst sha256 = (s: string) => createHash(\"sha256\").update(s).digest(\"hex\");\n\n@Injectable()\nexport class TokenService {\n  // Store only hashes of refresh tokens (here in memory; in production: Redis or a table).\n  private readonly refresh = new Map<string, RefreshRecord>();\n\n  constructor(private readonly jwt: JwtService) {}\n\n  async issue(user: User, familyId: string = randomUUID()) {\n    const claims: Claims = { sub: user.id, tid: user.tenantId, role: user.role, loc: user.locationId, pv: user.permVersion };\n    const accessToken = await this.jwt.signAsync(claims); // 15 min, see JwtModule options\n    const refreshToken = randomBytes(32).toString(\"base64url\");\n    this.refresh.set(sha256(refreshToken), { userId: user.id, familyId, used: false, expiresAt: Date.now() + 7 * 24 * 3600_000 });\n    return { accessToken, refreshToken, expiresIn: 900 };\n  }\n\n  // Rotation with reuse detection: an already used refresh token revokes the whole family.\n  async rotate(refreshToken: string) {\n    const record = this.refresh.get(sha256(refreshToken));\n    if (!record || record.expiresAt < Date.now()) throw new UnauthorizedException(\"Invalid refresh token\");\n    if (record.used) {\n      for (const [hash, r] of this.refresh) if (r.familyId === record.familyId) this.refresh.delete(hash);\n      throw new UnauthorizedException(\"Refresh token reuse detected – please sign in again\");\n    }\n    record.used = true;\n    const user = users.find((u) => u.id === record.userId);\n    if (!user) throw new UnauthorizedException(\"User no longer exists\");\n    return this.issue(user, record.familyId); // the new token carries the CURRENT role and permVersion\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/auth/auth.controller.ts"},"content":[{"type":"text","text":"import { Body, Controller, ForbiddenException, HttpCode, NotFoundException, Param, Patch, Post, UnauthorizedException } from \"@nestjs/common\";\nimport { z } from \"zod\";\nimport { users } from \"../data.js\";\nimport { CurrentUser, Public, type Claims } from \"./claims.js\";\nimport { TokenService } from \"./token.service.js\";\n\n@Controller()\nexport class AuthController {\n  constructor(private readonly tokens: TokenService) {}\n\n  // DEMO ONLY: signs in by user id. Real password/OAuth sign-in: see the authentication tutorial.\n  @Public()\n  @Post(\"auth/login\")\n  @HttpCode(200)\n  login(@Body({ schema: z.object({ userId: z.string() }) }) body: { userId: string }) {\n    const user = users.find((u) => u.id === body.userId);\n    if (!user) throw new UnauthorizedException(\"Unknown user\");\n    return this.tokens.issue(user);\n  }\n\n  @Public()\n  @Post(\"auth/refresh\")\n  @HttpCode(200)\n  refresh(@Body({ schema: z.object({ refreshToken: z.string().min(20) }) }) body: { refreshToken: string }) {\n    return this.tokens.rotate(body.refreshToken);\n  }\n\n  // Changing a role bumps permVersion → all existing access tokens of that user stop working.\n  @Patch(\"users/:id/role\")\n  changeRole(@CurrentUser() me: Claims, @Param(\"id\") id: string, @Body({ schema: z.object({ role: z.enum([\"manager\", \"cook\", \"courier\"]) }) }) body: { role: \"manager\" | \"cook\" | \"courier\" }) {\n    if (me.role !== \"owner\") throw new ForbiddenException(\"Only the owner manages roles\");\n    const user = users.find((u) => u.id === id && u.tenantId === me.tid);\n    if (!user) throw new NotFoundException(`User ${id} not found`);\n    user.role = body.role;\n    user.permVersion += 1;\n    return { id: user.id, role: user.role, permVersion: user.permVersion };\n  }\n}"}]}]}]},"toc":[{"id":"droga-zadania-przez-warstwy-autoryzacji","text":"Droga żądania przez warstwy autoryzacji","level":2,"locked":false},{"id":"rbac-abac-i-polityki-slownik","text":"RBAC, ABAC i polityki – słownik","level":2,"locked":false},{"id":"krok-1-projekt-i-modul","text":"Krok 1. Projekt i moduł","level":2,"locked":false},{"id":"krok-2-co-jest-w-tokenie","text":"Krok 2. Co jest w tokenie","level":2,"locked":false},{"id":"krok-3-guard-jwt-rotacja-i-natychmiastowe-odebranie-uprawnien","text":"Krok 3. Guard JWT, rotacja i natychmiastowe odebranie uprawnień","level":2,"locked":false},{"id":"krok-4-uprawnienia-w-jednym-miejscu-casl","text":"Krok 4. Uprawnienia w jednym miejscu: CASL","level":2,"locked":true},{"id":"krok-5-obiekt-pole-i-regula-biznesowa-w-serwisie","text":"Krok 5. Obiekt, pole i reguła biznesowa w serwisie","level":2,"locked":true},{"id":"wielodostepnosc-multi-tenant-na-co-uwazac","text":"Wielodostępność (multi-tenant): na co uważać","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":53,"visibleBlocks":18,"resources":[{"id":"6b0857b53c96f2d34d0b3903","type":"article","provider":"web","url":"https://www.alexanderlolis.com/authorization-in-a-microservices-world","embedUrl":null,"title":"Authorization in a Microservices World","description":"Authorization? How hard can it be? I am pretty sure that others have already solved it. We are not the first ones doing microservices. It should be easy to integrate what's already out there.","author":"alexanderlolis.com","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["microservices"],"techs":["general"],"tags":["software-architecture","hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2022-04-01T15:11:45.000Z","popularity":69,"verifiedAt":"2026-11-26T11:07:59.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:52.228Z","updatedAt":"2026-11-26T16:00:52.228Z"},{"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":"6b0857c73c96f2d34d0b4939","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=2_MFbm0fY0g","embedUrl":"https://www.youtube-nocookie.com/embed/2_MFbm0fY0g","title":"Multi-Tenant “Best Practices” Can Backfire","description":"Building a multi-tenant system often starts with standard \"best practices\": hiding the Tenant ID behind ambient context, relying on automatic global query filters, or using feature flags to branch behavior. But do these patterns actually remove complexity, or do they just move it? 🔔 Subscribe…","author":"CodeOpinion","thumbnailUrl":"https://i.ytimg.com/vi/2_MFbm0fY0g/hqdefault.jpg","durationSec":null,"lang":"en","topics":[],"techs":["dotnet"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2026-09-23T13:30:08.000Z","popularity":65,"verifiedAt":"2026-11-26T10:53:33.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857b73c96f2d34d0b3c41","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/pl/podcast/90-o-projektowaniu-architektury-multi-tenant-z-micha%C5%82em/id1508298430?i=1000677397792","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id1508298430?i=1000677397792","title":"90. O projektowaniu architektury multi-tenant z Michałem Giergielewiczem","description":"Architektura systemu nie jest jedynie pochodną wymagań funkcjonalnych. Istotny wpływ ma tu także fakt, czy z system powstaje do obsługi jednej organizacji, czy też będzie z niego korzystać wiele całkowicie osobnych firm, a także w jakim stopniu poszczególni użytkownicy będą wykorzystywać dostępne…","author":"Better Software Design","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts115/v4/a9/6d/bb/a96dbb46-a01a-9cf6-40ef-27a27cef3c73/mza_18038037312547630971.jpg/600x600bb.jpg","durationSec":4590,"lang":"pl","topics":[],"techs":["general"],"tags":["podcast","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2024-11-19T00:00:00.000Z","popularity":64,"verifiedAt":"2026-11-26T11:07:44.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:53.924Z","updatedAt":"2026-11-26T16:00:53.924Z"},{"id":"6b0857bf3c96f2d34d0b426f","type":"article","provider":"web","url":"https://aws.amazon.com/builders-library/fairness-in-multi-tenant-systems","embedUrl":null,"title":"Fairness in multi-tenant systems | AWS Builder Center","description":"How Amazon keeps shared, multi-tenant services fair, using throttling, quotas, and workload isolation so one tenant's traffic can't starve others.","author":"Amazon Builders' Library","thumbnailUrl":"https://builder.aws.com/assets/og-hiXAX-on.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["aws","distributed-systems","cloud"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2020-11-13T12:00:00.000Z","popularity":65,"verifiedAt":"2026-11-26T11:25:45.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"}],"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":104,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":46}]}}