RBAC in NestJS
This tutorial adds role-based access control (RBAC) to a NestJS API with node-casbin. Each route declares the permission it needs with a decorator, a global guard asks Casbin whether the current user has it, and roles inherit from each other, so an admin automatically gets everything an editor can do.
The permissions are named after resources and actions (articles, delete) instead of URL paths, which fits NestJS controllers well. For path-based rules, see the Express version.
1. Install
Start from a NestJS project (nest new my-app) and add Casbin:
npm install casbin
2. Write the model
Save this as model.conf in the project root:
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
r = sub, obj, act: each request is a user, a resource, and an action.g = _, _: users can be assigned to roles, and roles to other roles.g(r.sub, p.sub)is true when the user has the role in the policy rule, either directly or through inherited roles.