{"id":"6b09aa805a5e2dbc3f20a48f","slug":"nestjs-auth-rbac","title":"Authorization in NestJS 12 – guards, roles and permissions with CASL, JWT with refresh, and multi-tenancy","summary":"Authentication says who you are; authorization says what you may do with this particular resource. We build an API for a SaaS platform serving dumpling-restaurant chains: a global JWT guard, roles turned into CASL rules with conditions (location, courier, status) and field permissions, route policies, instant permission revocation after a role change, refresh token rotation and tenant isolation – with real HTTP responses.","servedLang":"en","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":20,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T16:06:24.765Z","updatedAt":"2026-11-27T17:28:37.681Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"tint","weaveResources":true,"toc":"right"},"seoDescription":"NestJS 12 authorization step by step – APP_GUARD with JWT, RBAC vs ABAC, CASL 7 (AbilityBuilder, createMongoAbility, subject, ForbiddenError, field permissions), @CheckPolicies, 401 vs 403 vs 404, a permission version in the token, refresh token rotation, multi-tenancy and PostgreSQL Row Level Secur","wordCount":3938,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Most API data leaks are not cracked passwords but a "},{"type":"text","text":"missing permission check on a specific object","marks":[{"type":"bold"}]},{"type":"text","text":": a signed-in user changes the "},{"type":"text","text":"id","marks":[{"type":"code"}]},{"type":"text","text":" in the URL and sees someone else's order (OWASP API Security calls it BOLA – Broken Object Level Authorization – and has ranked it first for years). A guard with a list of roles cannot solve this, because the role \"cook\" does not say in which location and at which order status a change is allowed. In this tutorial you will build authorization in layers – from the token, through a route policy, to object- and field-level rules – and verify each layer with a real request."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Authentication (401) ≠ authorization (403).","marks":[{"type":"bold"}]},{"type":"text","text":" A global JWT guard checks the token's signature, expiry, issuer and audience. What is allowed is decided by rules – ideally in one place (CASL), not in "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":"s scattered across controllers."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Roles are bundles of permissions; conditions turn them into ABAC.","marks":[{"type":"bold"}]},{"type":"text","text":" \"A cook may change "},{"type":"text","text":"only the status","marks":[{"type":"italic"}]},{"type":"text","text":" of orders "},{"type":"text","text":"in their own location","marks":[{"type":"italic"}]},{"type":"text","text":" "},{"type":"text","text":"while they are in the kitchen","marks":[{"type":"italic"}]},{"type":"text","text":"\" – that is a single CASL rule with fields and conditions."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The tenant comes from the token, never from the request.","marks":[{"type":"bold"}]},{"type":"text","text":" Other tenants' data answers 404, not 403. A role change bumps the permission version, so old tokens stop working immediately."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A SaaS API in NestJS 12 (ESM) for dumpling-restaurant chains: two tenants, owner / manager / cook / courier roles, sign-in with an access token (15 min) and a rotated refresh token, a global "},{"type":"text","text":"JwtAuthGuard","marks":[{"type":"code"}]},{"type":"text","text":", a CASL ability factory, a "},{"type":"text","text":"@CheckPolicies","marks":[{"type":"code"}]},{"type":"text","text":" decorator, object- and field-level checks in the service, a filter that turns CASL errors into 403, and a role change that invalidates old tokens. Plus a PostgreSQL Row Level Security example. You can download the code as a ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"Authentication: JWT, sessions and OAuth","marks":[{"type":"link","attrs":{"href":"/en/articles/authentication"}}]},{"type":"text","text":" (passwords, cookies, token rotation – here we only recap), "},{"type":"text","text":"NestJS in practice","marks":[{"type":"link","attrs":{"href":"/en/articles/nestjs"}}]},{"type":"text","text":", Node.js 24 LTS."}]},{"type":"stats","attrs":{"items":[{"value":"4","label":"control layers","hint":"token, route policy, object, field"},{"value":"401 / 403 / 404","label":"three different answers","hint":"who you are, what is allowed, does it exist at all"},{"value":"15 min","label":"access token lifetime","hint":"refresh token rotated on every use"},{"value":"1","label":"place for rules","hint":"the CASL `AbilityFactory`"}]}},{"type":"heading","attrs":{"level":2,"id":"a-request-s-path-through-the-authorization-layers"},"content":[{"type":"text","text":"A request's path through the authorization layers"}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  R[\"PATCH /orders/o-1001<br/>Authorization: Bearer …\"] --> G1{\"JwtAuthGuard<br/>signature, exp, iss, aud,<br/>permission version\"}\n  G1 -->|\"no\"| E401[\"401 Unauthorized\"]\n  G1 -->|\"yes\"| G2{\"PoliciesGuard<br/>can this role access<br/>the resource at all?\"}\n  G2 -->|\"no\"| E403a[\"403 Forbidden\"]\n  G2 -->|\"yes\"| P[\"Pipe: Zod schema<br/>(unknown fields = 400)\"]\n  P --> S1{\"Service: order<br/>in my tenant?\"}\n  S1 -->|\"no\"| E404[\"404 Not Found\"]\n  S1 -->|\"yes\"| S2{\"CASL: object and fields<br/>location, courier, status\"}\n  S2 -->|\"no\"| E403b[\"403 Forbidden\"]\n  S2 -->|\"yes\"| S3{\"Business rules<br/>allowed status transition?\"}\n  S3 -->|\"no\"| E400[\"400 Bad Request\"]\n  S3 -->|\"yes\"| OK[\"200 OK\"]","caption":"Successive gates in NestJS – each answers with a different status"}},{"type":"heading","attrs":{"level":2,"id":"rbac-abac-and-policies-a-glossary"},"content":[{"type":"text","text":"RBAC, ABAC and policies – a glossary"}]},{"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":"Question"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Where in code"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"RBAC (roles)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"What is your role?\""}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"only the owner manages roles"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"role","marks":[{"type":"code"}]},{"type":"text","text":" in the token, "},{"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 (attributes)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"What are the user's and the resource's attributes?\""}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a cook – orders of their location with status \"in the kitchen\""}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"conditions in CASL rules"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Field permissions"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"Which fields may you change?\""}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a cook changes "},{"type":"text","text":"status","marks":[{"type":"code"}]},{"type":"text","text":", not "},{"type":"text","text":"totalCents","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the field list in a CASL rule"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ReBAC (relationships)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"How are you related to the resource?\""}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the courier assigned to the order"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the "},{"type":"text","text":"courierId: user.sub","marks":[{"type":"code"}]},{"type":"text","text":" condition (for complex graphs: OpenFGA, SpiceDB)"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"step-1-project-and-module"},"content":[{"type":"text","text":"Step 1. Project and module"}]},{"type":"codeGroup","attrs":{"title":"Configuration, bootstrap and the app module"},"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":" as ","marks":[{"type":"bold"}]},{"type":"text","text":"APP_GUARD","marks":[{"type":"code"}]},{"type":"text","text":" – every route requires a token unless marked "},{"type":"text","text":"@Public()","marks":[{"type":"code"}]},{"type":"text","text":". A safe default: a forgotten decorator means \"closed\", not \"open\"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"verifyOptions","marks":[{"type":"code"}]},{"type":"text","text":" with ","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":" and ","marks":[{"type":"bold"}]},{"type":"text","text":"audience","marks":[{"type":"code"}]},{"type":"text","text":" – a token issued for another service or signed with a different algorithm is rejected. The secret has at least 32 characters and comes from an environment variable; the app won't start without it."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"StandardSchemaValidationPipe","marks":[{"type":"code"}]},{"type":"text","text":" (Nest 12) validates request bodies with Zod schemas; "},{"type":"text","text":".strict()","marks":[{"type":"code"}]},{"type":"text","text":" in the update schema turns unknown fields into a 400 error."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"step-2-what-goes-into-the-token"},"content":[{"type":"text","text":"Step 2. What goes into the token"}]},{"type":"codeGroup","attrs":{"title":"Claims, decorators and demo data"},"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":"The token contains only what authorization needs: "},{"type":"text","text":"sub","marks":[{"type":"code"}]},{"type":"text","text":" (user), "},{"type":"text","text":"tid","marks":[{"type":"code"}]},{"type":"text","text":" (tenant), "},{"type":"text","text":"role","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"loc","marks":[{"type":"code"}]},{"type":"text","text":" (location) and "},{"type":"text","text":"pv","marks":[{"type":"code"}]},{"type":"text","text":" – the "},{"type":"text","text":"permission version","marks":[{"type":"bold"}]},{"type":"text","text":". No e-mails or names: a JWT is signed, not encrypted, so anyone who has it can read its contents."}]},{"type":"output","attrs":{"title":"POST /auth/login response (shortened) and the decoded access token payload","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":"step-3-the-jwt-guard-rotation-and-instant-permission-revocation"},"content":[{"type":"text","text":"Step 3. The JWT guard, rotation and instant permission revocation"}]},{"type":"codeGroup","attrs":{"title":"Guard, token service and auth controller"},"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":"a-request-s-path-through-the-authorization-layers","text":"A request's path through the authorization layers","level":2,"locked":false},{"id":"rbac-abac-and-policies-a-glossary","text":"RBAC, ABAC and policies – a glossary","level":2,"locked":false},{"id":"step-1-project-and-module","text":"Step 1. Project and module","level":2,"locked":false},{"id":"step-2-what-goes-into-the-token","text":"Step 2. What goes into the token","level":2,"locked":false},{"id":"step-3-the-jwt-guard-rotation-and-instant-permission-revocation","text":"Step 3. The JWT guard, rotation and instant permission revocation","level":2,"locked":false},{"id":"step-4-permissions-in-one-place-casl","text":"Step 4. Permissions in one place: CASL","level":2,"locked":true},{"id":"step-5-object-field-and-business-rule-in-the-service","text":"Step 5. Object, field and business rule in the service","level":2,"locked":true},{"id":"multi-tenancy-what-to-watch-out-for","text":"Multi-tenancy: what to watch out for","level":2,"locked":true},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":true},{"id":"check-yourself","text":"Check yourself","level":2,"locked":true},{"id":"what-next","text":"What next","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":"Authority","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":46}]}}