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:
RolePolicyandPermissionPolicy(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
Gatefor 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-authzImport both modules:
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:
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:
@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
- Policies — official
@Policy()classes, plus@PolicyFor(Resource)and theAuthzPolicybase (super-admin and the external engine inbefore()). - Gates — a service-layer
GateoverAuthorizationService, with string abilities, ad-hoc gates, batches and query scopes. - 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.8 | 0.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, PolicyRegistry | removed: the official AuthorizationGuard; PolicyIndex |
AuthzModule.forRoot({ policies }) | register policies as providers (or AuthorizationModule.forRoot({ policies })) |
superAdmin applied everywhere | applied by AuthzPolicy subclasses, the built-in policies and the Gate |
after hook, { allowed, message } results | removed: only a literal true allows |
| current user from nestjs-context on routes | the official getUser (default request.user) |
gate.allows() user from nestjs-context | AuthenticationContext.user inside its scope (null there is a guest), nestjs-context outside it |
| a persisted permission named like a policy ability grants it | the policy decides (only superAdmin bypasses it), in checks and in scope() |
DecisionProvider / superAdmin see a guest as undefined | null |
a DecisionProvider deny message ({ allowed: false, message }) is the 403's message | dropped: 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 check | asked 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):
-
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 ]AuthzModuleregisters its own globalAuthzGuard. A route with official@Can()requirements (class or method,@Roles,@Permission) is handed to the officialAuthorizationGuardas is: samegetUser, same policies, same 401 for a guest and 403 for a user, samedeniedevent. 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/authorizationchecks at startup that a guard enforces each@Can(), and it recognizes only its ownAuthorizationGuard. It does not seeAuthzGuard, 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:
AuthzGuardenforces those handlers, andAuthzModulelogs a line right after it naming them. The error goes away at step 4. -
Drop the 0.8 guard and move the old decorators. Remove
RolesGuard/CanGuardfromAPP_GUARDand@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 byAuthzGuard. -
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. -
Switch to deny by default when every route declares something: remove
unannotated(or set'deny') andglobalGuard: 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
Getting Started
Install, import the modules, write a policy, guard a route, check in a service.
Policies
Official policies, @PolicyFor, AuthzPolicy and superAdmin.
Gates
The service-layer Gate: string abilities, define, allowsMany, scope.
Enforcement
The official guard, our @Can helpers, @Roles/@Permission, the can-endpoint.
Current user
getUser on routes; AuthenticationContext and nestjs-context for the Gate.
Resource resolution
byId, ResourceResolver and authorizedResource.
RBAC
RolePolicy / PermissionPolicy and the ORM adapters.
External engines
Cerbos, OPA and any PDP through DECISION_PROVIDER.
Ecosystem
Inertia, codegen, React, testing and Telescope.