skip to content

In a NestJS 12 app using @nestjs/authorization, how do @Policy() classes, @Can() and authorize() split an orders API's checks?

level: middleimportance: should knowfreq 25%

answer

  1. abilities are policy methods
  2. route check without a record
  3. record check in the service
  4. can() answers, authorize() throws
  5. before() runs ahead of abilities

basics

~20 s

A @Policy() class holds abilities, methods taking the user that return true to allow. @Can() checks an ability in the global guard before the handler, for rules needing no record; authorize() checks it in the service after loading the order.

solid answer

~40 s

In NestJS 12, `@nestjs/authorization` models permissions as `@Policy()` classes, injectable singletons whose abilities take the user first and allow only on a literal `true`. `@Can(Policy, 'ability')` on a route makes the global `AuthorizationGuard` run the ability before the handler, which suits rules that need no record (the ability must accept a `null` user); a third argument can read an id from the URL. Rules that depend on the order itself go in the service: load it, then `authorizationService.authorize(OrderPolicy, 'view', user, order)`, which throws an `AuthorizationError` that becomes a 401 or 403 when it leaves the handler, while `can()` returns a boolean for shaping lists and flags. Those routes declare `@Can.Anyone()` because the guard denies undeclared handlers. A `before()` hook can let admins through, but it skips every ability unless it checks the ability name.

code

typescript · 70 lines
typescript
import { Controller, Get, Injectable, NotFoundException, Param } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { AuthorizationService, Can, Policy, type Ability, type PolicyBefore } from '@nestjs/authorization';

type Role = 'customer' | 'staff' | 'admin';
interface User { id: string; roles: Role[] }
interface Order { id: string; userId: string; status: 'paid' | 'shipped' | 'refunded' }

@Policy()
export class OrderPolicy implements PolicyBefore<User, Ability<OrderPolicy>> {
  // Admins pass every check except refunds, which bind everyone.
  before(user: User | null, ability: Ability<OrderPolicy>) {
    if (ability !== 'refund' && user?.roles.includes('admin')) {
      return true;
    }
  }

  viewAll(user: User) {
    return user.roles.includes('staff');
  }

  view(user: User, order: Order) {
    return order.userId === user.id || user.roles.includes('staff');
  }

  refund(user: User, order: Order) {
    return user.roles.includes('staff') && order.status === 'paid';
  }
}

@Injectable()
export class OrdersService {
  private readonly orders: Order[] = [];

  constructor(private readonly authorizationService: AuthorizationService) {}

  async findAll(user: User) {
    // A question the query can use: filter in the database, not row by row.
    return (await this.authorizationService.can(OrderPolicy, 'viewAll', user))
      ? this.orders
      : this.orders.filter((order) => order.userId === user.id);
  }

  async findOne(user: User, id: string) {
    const order = this.orders.find((candidate) => candidate.id === id);
    if (!order) {
      throw new NotFoundException();
    }
    // Throws AuthorizationError on denial; it becomes a 401 or 403 when it leaves the handler.
    await this.authorizationService.authorize(OrderPolicy, 'view', user, order);
    return order;
  }
}

@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Get()
  @Can.Anyone() // the service decides what each caller sees
  findAll(@CurrentUser() user: User) {
    return this.ordersService.findAll(user);
  }

  @Get(':id')
  @Can.Anyone()
  findOne(@CurrentUser() user: User, @Param('id') id: string) {
    return this.ordersService.findOne(user, id);
  }
}

go deeper

for a junior

Recall the vocabulary: a @Policy() class with ability methods, @Can() on a route, and authorize() or can() from AuthorizationService in a service.

for a middle

Explain which checks go on the route and which in the service, why @Can() cannot take a record, and how can() and authorize() differ on a denial.

for a senior

Show the production edges: before() bypasses that must spare binding rules, filtering lists in the query, 403 versus 404 for sensitive records, and singleton policies.

for a principal

Weigh where a team's rules should live so controllers, resolvers and workers share them, and what the typed policy surface buys compared with string role checks.

## Policies: permissions as provider classes `@nestjs/authorization`, taught by the NestJS 12 security docs, expresses permissions as **policies**. A policy is a class decorated with `@Policy()`; each method whose first parameter is the user and which returns `boolean` or `Promise<boolean>` is an **ability**. `@Policy()` also makes the class injectable, so a policy is an ordinary provider: register it in its feature module's `providers` and the authorization module discovers it, or list it in the `policies` option of `AuthorizationModule.forRoot()`. A policy can inject services, such as a per-person refund limit, and it must be a singleton: a request-scoped or transient policy throws at startup. For an orders API where customers see only their own orders, staff see all of them and admins bypass most checks, the policy might hold: - `viewAll(user)`: may this user list every order? - `view(user, order)`: may this user see this order? - `refund(user, order)`: may this user refund this order? Only a literal `true` allows. Any other value denies, even a truthy one. ## Three ways to ask | Tool | Where it runs | On denial | Use it for | |---|---|---|---| | `@Can(Policy, 'ability')` | on a handler or controller, enforced by the global `AuthorizationGuard` before the handler | the guard throws a 401 or a 403 | checks that need no record | | `authorize(Policy, 'ability', user, ...args)` on `AuthorizationService` | in a service, after loading the record | throws `AuthorizationError`, turned into a 401 or 403 when it leaves the handler | record-by-record checks | | `can(...)` on `AuthorizationService` | anywhere | resolves to `false`, never throws | shaping responses, choosing a query | The split follows what each check needs: 1. **No record needed** ("only staff may export every order"): `@Can()` on the route. The guard calls the ability with the user alone, so the ability must accept a `null` user. 2. **An identifier from the URL** ("may this user list customer X's orders?"): still `@Can()`, with a third argument that reads the parameter from the `ExecutionContext`. It runs in the guard, before any pipe, so it receives the raw string. 3. **The record itself** ("may this customer see order 42?"): load the order in the service, then call `authorize(OrderPolicy, 'view', user, order)`. The route declares `@Can.Anyone()`, so the guard lets the call through to the service. 4. **A list**: ask a question the query can use, `can(OrderPolicy, 'viewAll', user)`, and filter in the database rather than checking every row. Checking records in the service means a controller, a resolver and a queue worker calling the same method all get the same rule. ## Type checking does the bookkeeping `@Can()` and `AuthorizationService` are typed from the ability's own signature: - A misspelled ability does not compile, and the error lists the valid names. - `@Can()` accepts only abilities whose user parameter accepts `null`, because the guard cannot know whether a route has a user. An ability that only services call may take `User`, which forces callers to rule out a guest first. - An ability that accepts a `null` user but also takes a record still fails in `@Can()` without a resolver: for `view(user: User | null, order: Order)`, `@Can(OrderPolicy, 'view')` gives `Expected 3 arguments, but got 2`, because the guard has no order to pass. - At startup, a `@Can()` naming a policy nobody registered stops the app, and the error names the handler. ## Admins and `before()` Rather than add an admin clause to every ability, give the policy a `before()` hook. It runs ahead of every ability of its policy, for route checks and service checks alike, and receives the user, the ability name and the ability's arguments. Return `true` to allow, `false` to deny, or nothing to let the ability decide. Guests reach it too, so its user parameter must accept `null`; `before(user: User)` does not compile. The catch: the hook skips *every* ability, including rules meant to bind everyone, such as "nobody refunds a shipped order". The docs' remedy is to check the ability name the hook receives and return nothing for the abilities it must not skip, typing the name as `Ability<OrderPolicy>` so a misspelled exclusion fails to compile. In unit tests, calling an ability directly skips `before()`; going through `AuthorizationService` runs both. ## What every route must declare `AuthorizationModule.forRoot()` registers `AuthorizationGuard` as a global guard, and that guard denies by default: a handler runs only when it, or its class, declares `@Can()`, `@Can.Anyone()`, or `@Public()` from `@nestjs/authentication`. That is why orders routes that check in the service still carry `@Can.Anyone()`: without it, the guard would deny them before the service ever ran.

  • Why not load the order inside a @Can() argument resolver so the check stays on the route?
    The resolver runs in the guard, before any pipe, so it would load the order once for the check and again in the handler. It would also answer 403 before the handler could answer 404 for a missing order. The NestJS 12 docs say to pass identifiers and scopes to `@Can()`, not records, and to check records in the service with `authorize()`.
  • When does a 403 from authorize() leak information, and what do you do instead?
    A 403 confirms that the order exists. When ids are sequential or guessable and existence is sensitive, call `can()` instead, which resolves to `false` without throwing, and throw a `NotFoundException` yourself, so a forbidden order looks the same as a missing one.
  • Why must a policy be a singleton, and where does per-request data go?
    The authorization module resolves each policy once and shares it across all requests, so a request-scoped or transient policy, or one depending on a request-scoped provider, throws at startup. Anything that varies per request, the user, the record, an id, is passed to the ability as an argument.

  • An ability that returns any truthy value allows the action.
  • Record checks belong in @Can(), by loading the record in its resolver.
  • authorize() returns false on a denial, like can().
  • A before() admin bypass only affects checks made with @Can() on routes.
  • Routes that check in the service need no declaration on the handler.

Assumes NestJS 12, whose security docs introduce the first-party @nestjs/authorization package with @Policy(), @Can() and AuthorizationService.