Polski

Tutorial · NestJS · Authentication

Authorization in NestJS 12 – guards, roles and permissions with CASL, JWT with refresh, and multi-tenancy

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.

By · · 20 min read

Most API data leaks are not cracked passwords but a missing permission check on a specific object: a signed-in user changes the id 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.

Prerequisites: Authentication: JWT, sessions and OAuth (passwords, cookies, token rotation – here we only recap), NestJS in practice, Node.js 24 LTS.

4
control layers – token, route policy, object, field
401 / 403 / 404
three different answers – who you are, what is allowed, does it exist at all
15 min
access token lifetime – refresh token rotated on every use
1
place for rules – the CASL `AbilityFactory`

A request's path through the authorization layers

Diagram: Successive gates in NestJS – each answers with a different status

RBAC, ABAC and policies – a glossary

ModelQuestionExampleWhere in code
RBAC (roles)"What is your role?"only the owner manages rolesrole in the token, @CheckPolicies
ABAC (attributes)"What are the user's and the resource's attributes?"a cook – orders of their location with status "in the kitchen"conditions in CASL rules
Field permissions"Which fields may you change?"a cook changes status, not totalCentsthe field list in a CASL rule
ReBAC (relationships)"How are you related to the resource?"the courier assigned to the orderthe courierId: user.sub condition (for complex graphs: OpenFGA, SpiceDB)

Step 1. Project and module

Configuration, bootstrap and the app module

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 as APP_GUARD – every route requires a token unless marked @Public(). A safe default: a forgotten decorator means "closed", not "open".
  • verifyOptions with algorithms: ["HS256"], issuer and audience – 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.
  • StandardSchemaValidationPipe (Nest 12) validates request bodies with Zod schemas; .strict() in the update schema turns unknown fields into a 400 error.

Step 2. What goes into the token

Claims, decorators and demo data

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 },
];

The token contains only what authorization needs: sub (user), tid (tenant), role, loc (location) and pv – the permission version. No e-mails or names: a JWT is signed, not encrypted, so anyone who has it can read its contents.

POST /auth/login response (shortened) and the decoded access token payload
{ "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"}

Step 3. The JWT guard, rotation and instant permission revocation

Guard, token service and auth controller

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 };
  }
}

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 4. Permissions in one place: CASL
  • Step 5. Object, field and business rule in the service
  • Multi-tenancy: what to watch out for
  • Common mistakes
  • Check yourself
  • What next

Create a free account · Sign in