Advanced Authorization: Policies & CASL
Advanced Authorization: Policies & CASL
RBAC answers "does this user have the admin role?" But real apps need finer rules: "can this user edit this specific article?" That depends on the user, the action, and the resource together. Policy-based (or attribute-based) authorization handles this, and CASL is the most popular library for it in the NestJS world.
Why RBAC is not enough
Consider editing an article. The rule is "a user can edit an article they authored, OR any article if they are an admin." Pure RBAC cannot express the ownership half — the decision depends on comparing the user to the resource. This is where policies shine.
Defining abilities with CASL
CASL describes permissions as abilities: combinations of an action (read, update, delete) and a subject (a model), optionally with conditions:
manage and all are CASL wildcards meaning "any action" and "any subject". The condition { authorId: user.id } is the ownership rule RBAC could not express.
Checking an ability
ability.can('update', article) evaluates the condition against the actual article instance — comparing its authorId to the user. That is the leap beyond role checks.
Integrating with NestJS
The idiomatic pattern is a CaslAbilityFactory provider that builds abilities for a user, plus a policies guard that evaluates a declared policy. A @CheckPolicies() decorator attaches the rule, and the guard enforces it:
Choosing the right model
- RBAC — simple role gates ("admins only"). Use it when permissions map cleanly to roles.
- Policy/ABAC (CASL) — rules involving ownership, conditions, or resource attributes. Use it when "it depends on the resource".
Summary
Policy-based authorization (with CASL) expresses rules that depend on the action, the subject, and resource conditions — like editing only your own content — which RBAC cannot. Define abilities with can/cannot, check them resource-aware with ability.can(action, resource), and integrate via a policies guard and @CheckPolicies(). Use RBAC for coarse roles and policies for fine ownership rules. This completes Phase 6 — your APIs are now properly authenticated and authorized. Next: API design.