Aviary

Authz

Extras on top of NestJS's first-party @nestjs/authorization — persisted RBAC as official policies, @Can helpers, a service-layer Gate, super-admin, external engines and query scopes.

@dudousxd/nestjs-authz builds on NestJS's first-party @nestjs/authorization. Policies (@Policy()), route checks (@Can(Policy, 'ability', args?), Can.Anyone()), the global deny-by-default AuthorizationGuard, the current user (getUser) and AuthorizationService all come from the official package: read its docs first. This package adds only what the official one lacks:

  • Persisted RBAC as official policies: RolePolicy and PermissionPolicy (wildcards, tenant-scoped roles, direct permissions, role sources), backed by the TypeORM / MikroORM / Prisma / Drizzle adapters and fetched once per request.
  • Helpers for the official @Can(): byId(Post), roles(...), permission(...), ability(...), staticCanArgs(...); sugar @Roles(...) / @Permission(...).
  • A global super-admin and an external policy engine (Cerbos, OPA, …), honored by policies that extend AuthzPolicy.
  • A Gate for services: string abilities, policy-class checks, batches (allowsMany), ad-hoc gates (define), roles, query scopes (scope + the adapters' applyScope).
  • Frontend and tooling: Inertia props, a typed can() from codegen, client/React helpers, test helpers, and an allow + deny decision event for Telescope.

Quickstart

Install the official package and the extras:

pnpm add @nestjs/authorization @dudousxd/nestjs-authz

Import both modules:

app.module.ts
import { Module } from '@nestjs/common';
import { AuthorizationModule } from '@nestjs/authorization';
import { AuthzModule } from '@dudousxd/nestjs-authz';
import { PostPolicy } from './post.policy';

@Module({
  imports: [
    AuthorizationModule.forRoot(), // official: guard, @Can, AuthorizationService
    AuthzModule.forRoot({ superAdmin: (user) => user?.isRoot === true }),
  ],
  providers: [PostPolicy],
})
export class AppModule {}

Write an official policy; @PolicyFor links it to its resource for the extras:

post.policy.ts
import { Policy } from '@nestjs/authorization';
import { AuthzPolicy, PolicyFor } from '@dudousxd/nestjs-authz';

@Policy()
@PolicyFor(Post)
export class PostPolicy extends AuthzPolicy {
  update(user: User | null, post: Post) {
    return post.authorId === user?.id;
  }
}

Guard the route with the official @Can and our byId helper:

posts.controller.ts
@Patch(':id')
@Can(PostPolicy, 'update', byId(Post)) // loads the Post named by :id
update(@Req() req: Request) {
  const post = authorizedResource(req, Post); // the record byId loaded
}

A guest is answered 401, a signed-in user 403. The route user is the official getUser (default request.user).

Authorization, not authentication

Authz answers "what may this user do?", never "who is this user?". Bring your own authentication (@nestjs/authentication, Passport, a JWT guard); the official guard reads the user it produced.

What this package adds

  1. Policies — official @Policy() classes, plus @PolicyFor(Resource) and the AuthzPolicy base (super-admin and the external engine in before()).
  2. Gates — a service-layer Gate over AuthorizationService, with string abilities, ad-hoc gates, batches and query scopes.
  3. RBAC — persisted roles and permissions as RolePolicy / PermissionPolicy, through an opt-in ORM adapter. The core stays zero-DB.

Migrating from 0.8

0.8 and earlier had their own engine. 0.9 runs on @nestjs/authorization, and the old decorators are gone: move each one to its official form.

0.80.9
@Policy(Post)@Policy() from @nestjs/authorization + @PolicyFor(Post) (or @PolicyFor(Post) alone)
@Can('update', Post)@Can(PostPolicy, 'update', byId(Post)), @Can from @nestjs/authorization
@Can('create', Post, { classLevel: true })@Can(PostPolicy, 'create')
@Can('access-admin')@Can(GatePolicy, 'allows', ability('access-admin'))
@Roles('admin') + RolesGuard@Roles('admin'), enforced by the official guard
CanGuard, RolesGuard, PolicyRegistryremoved: the official AuthorizationGuard; PolicyIndex
AuthzModule.forRoot({ policies })register policies as providers (or AuthorizationModule.forRoot({ policies }))
superAdmin applied everywhereapplied by AuthzPolicy subclasses, the built-in policies and the Gate
after hook, { allowed, message } resultsremoved: only a literal true allows
current user from nestjs-context on routesthe official getUser (default request.user)
gate.allows() user from nestjs-contextAuthenticationContext.user inside its scope (null there is a guest), nestjs-context outside it
a persisted permission named like a policy ability grants itthe policy decides (only superAdmin bypasses it), in checks and in scope()
DecisionProvider / superAdmin see a guest as undefinednull
a DecisionProvider deny message ({ allowed: false, message }) is the 403's messagedropped: the 403 is the official { statusCode: 403, message: 'Forbidden' }. To send a reason, throw your own ForbiddenException(reason) from the ability; a route then gets your body, but no denied event is emitted and AuthorizationService.can() throws instead of returning false. See External engines.
DecisionProvider asked by the Gate on every checkasked by AuthzPolicy.before() on routes, and by Gate string abilities
import … from '@dudousxd/nestjs-authz-inertia/client'import … from '@dudousxd/nestjs-authz-client' (the subpath is removed)

Behavior the official guard brings

Deny by default: a handler with no @Can() is denied; add @Can.Anyone() (or @Public() from @nestjs/authentication) where anyone may call it. Class and method requirements add up. Guests reach the policy as null: type the user User | null; a guest denial is a 401. Deny by default is what the migration mode below defers.

Migrating one controller at a time: unannotated: 'allow'

The official guard denies every route that declares no @Can(): the app's public routes, and every controller another library mounts. 0.8 let them through. Turning authorization on for a large app in one go is rarely possible, so this package has a migration mode (the official guard has no such option):

  1. Turn the official global guard off, and switch the migration mode on:

    imports: [
      AuthenticationModule.forRoot({ ... }),                 // or your Passport guard, first
      AuthorizationModule.forRoot({ globalGuard: false }),
      AuthzModule.forRoot({ unannotated: 'allow' }),         // forRootAsync: next to useFactory
    ]

    AuthzModule registers its own global AuthzGuard. A route with official @Can() requirements (class or method, @Roles, @Permission) is handed to the official AuthorizationGuard as is: same getUser, same policies, same 401 for a guest and 403 for a user, same denied event. A route with no requirement is let through. The app fails to start if the official global guard is still on, because it would keep denying them.

    The boot log has one expected ERROR in this mode. @nestjs/authorization checks at startup that a guard enforces each @Can(), and it recognizes only its own AuthorizationGuard. It does not see AuthzGuard, so it logs:

    ERROR [Authorization] @Can() is not enforced on PostController.update, … : AuthorizationModule has
    globalGuard: false, and these handlers have no @UseGuards(AuthorizationGuard).

    That is safe: AuthzGuard enforces those handlers, and AuthzModule logs a line right after it naming them. The error goes away at step 4.

  2. Drop the 0.8 guard and move the old decorators. Remove RolesGuard / CanGuard from APP_GUARD and @UseGuards(), and rewrite each string @Can / @Policy(Post) with the table above (@Can('page.documents') → @Can(GatePolicy, 'allows', ability('page.documents'))). @Roles('admin') and @Permission(...) are unchanged. All of them are enforced by AuthzGuard.

  3. Annotate the open routes, one controller at a time: @Can.Anyone() where anyone may call it, @Public() (from @nestjs/authentication) where no sign-in is needed, a @Can(...) everywhere else.

  4. Switch to deny by default when every route declares something: remove unannotated (or set 'deny') and globalGuard: false. The official guard is global again, and a forgotten @Can() is a 403 instead of an open route.

A route that slipped through in step 3 is open in this mode, so keep it for the migration only.

Where to go next

On this page