惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
N
Netflix TechBlog - Medium
M
MIT News - Artificial intelligence
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Check Point Blog
The GitHub Blog
The GitHub Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Proofpoint News Feed
Martin Fowler
Martin Fowler
大猫的无限游戏
大猫的无限游戏
GbyAI
GbyAI
博客园_首页
A
About on SuperTechFans
Blog — PlanetScale
Blog — PlanetScale
人人都是产品经理
人人都是产品经理
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
T
The Blog of Author Tim Ferriss
The Cloudflare Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
ABAC and CASL with NestJS
Emmanuel Sun · 2026-05-27 · via DEV Community

A few days ago, I published an article that introduced an optimal way to handle permissions in Node.js in its entirety.

It's an approach that dismisses you from hard-locking permissions from arbitrary statements like "Pharmacy can perform this," "if (!Pharmacy) throw error," etc.

It's a common concept known as Attribute-Based Access Control (ABAC), which you'll find in advanced systems.

This article will address why and how to get this done in NestJS.

NB: We'll be speaking in NestJS language for the sake of this article.

When RBAC Fails

Maintainability

Imagine you have an app with multiple roles — pharmacy, customer, doctor — and you've handled all the necessary role handling.

Enough…

@Roles(Roles.Pharmacy)

Enter fullscreen mode Exit fullscreen mode

And more than enough…

@UseGuard(RolesGuard)

Enter fullscreen mode Exit fullscreen mode

…across your controllers.

The moment there's a need to create an Admin role, you'll find yourself scavenging to add Roles.ADMIN everywhere possible across controllers.

You'll also then need to sit down and spend hours, if not days, making sure all your if (!Roles.Pharmacy) throw error statements across services now include !Roles.Admin.

Sad to say, but this is decoupled code.

Scalability

Role-Based Access Control (RBAC) is only manageable with 2 roles.

A system that, by any means, has more than 2 roles will struggle to be maintained.

Imagine building a Google Cloud clone while using if (!Roles.Pharmacy) throw error — you quickly realize the bottlenecks.

Lack of Reusability

It's always necessary to handle permissions at the service level as well as at the controller level.

It's a lot cleaner at the controller level with a Roles decorator.

We can't say the same for the service level. You'll always end up with a myriad of if (!pharmacy) throw error statements across methods.

Imagine doing this over and over again for an application with multiple resources.

ABAC and CASL

ABAC introduces permission handling from a discrete standpoint.

I could equate role-based permission to knowing the smallest particle of "elements" as atoms, and one day realizing there exist "protons," "electrons," and "neutrons."

That's exactly what we do with ABAC.

Instead of focusing on "this is a hydrogen atom" and its characteristics, we are rather concerned with the constituents of the hydrogen atom.

We could even use our knowledge of these constituents to simulate other elements.

Enough chemistry. Let's get to the nitty-gritty.

TL;DR: ABAC moves away from "Who are you?" (role) to "Are you allowed to perform this specific action on this specific object?". CASL is a framework around ABAC.

NestJS Implementation

The first thing you do is create policies.

Policies allow you to control who can do what per resource.

This is properly known as "ability" in CASL.

Here's what it looks like for an inventory resource:

// inventory/inventory.ability.ts
import { AbilityBuilder } from '@casl/ability';

export function InventoryAbility(user, builder: AbilityBuilder<any>) {
  const { can, cannot } = builder;

  if (user.role === 'pharmacy') {
    can('create', 'Inventory');
    can('update', 'Inventory', {
      pharmacyId: user.pharmacyId,
    });
    can('read', 'Inventory');
  }

  if (user.role === 'customer') {
    can('read', 'Inventory');
  }

  if (user.role === 'admin') {
    can('manage', 'all');
  }

  cannot('delete', 'Inventory');
}

Enter fullscreen mode Exit fullscreen mode

For a NestJS execution, we'll create these for every resource we have.

This allows us to control who can do what per resource.

Next, we'll register this "ability" in our ability factory.

// ability.factory.ts
import { Injectable } from '@nestjs/common';
import { AbilityBuilder, Ability } from '@casl/ability';
import { InventoryPolicy } from './policies/inventory.policy';
import { MedicalPolicy } from './policies/medical.policy';
import { OrderPolicy } from './policies/order.policy';

@Injectable()
export class AbilityFactory {
  createForUser(user) {
    const builder = new AbilityBuilder(Ability);

    InventoryPolicy(user, builder);
    MedicalPolicy(user, builder);
    OrderPolicy(user, builder);

    return builder.build();
  }
}

Enter fullscreen mode Exit fullscreen mode

This is syntax that allows us to register our "abilities" to a central system provided by CASL, so we can access them anywhere in our codebase.

Next, we create an authorization guard.

We'll call this ability.guard.ts.

Your guard then becomes a clean, reusable piece of infrastructure.

// auth/casl/abilities.guard.ts
import {
  CanActivate,
  ExecutionContext,
  Injectable,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AbilityFactory } from './ability.factory';

@Injectable()
export class AbilitiesGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private abilityFactory: AbilityFactory,
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context
      .switchToHttp()
      .getRequest();
    const user = request.user;
    const ability =
      this.abilityFactory.createForUser(user);
    const abilityHandler = this.reflector.get(
      'ability',
      context.getHandler(),
    );

    return abilityHandler
      ? abilityHandler(ability)
      : true;
  }
}

Enter fullscreen mode Exit fullscreen mode

This ensures we authorize based on ability definitions in our controller.

We'll also create an Ability decorator.

// auth/casl/check-abilities.decorator.ts
import { SetMetadata } from '@nestjs/common';

export const CheckAbilities = (handler) =>
  SetMetadata('ability', handler);

Enter fullscreen mode Exit fullscreen mode

Using CASL

Authorization at the controller level becomes very declarative.

We can now comfortably have this:

@Get(':id')
@UseGuards(AbilitiesGuard)
@CheckAbilities((ability) =>
  ability.can('read', 'Inventory'),
)
async getInventory(
  @Param('id') id: string,
) {
  return this.inventoryService.findOne(id);
}

Enter fullscreen mode Exit fullscreen mode

Instead of passing a "Roles.PHARMACY" like we normally do with a Roles Guard, we check "who can actually read inventory."

Because in the future, we could want a doctor to. We may want a customer too. We could change the roles from pharmacy to something else.

This is easily feasible with our implementation.

Reusable. Maintainable. Scalable.

Now, a service protection example would look like this:

async updateInventory(
  user,
  inventoryId: string,
  updateData,
) {
  const inventory =
    await this.inventoryRepo.findOne(inventoryId);
  const ability =
    this.abilityFactory.createForUser(user);

  if (ability.cannot('update', inventory)) {
    throw new ForbiddenException(
      'You do not own this inventory record.',
    );
  }

  return this.inventoryRepo.update(
    inventoryId,
    updateData,
  );
}

Enter fullscreen mode Exit fullscreen mode


I'm a solo developer who's currently a free agent — openly looking for software engineering roles. My portfolio is at www.me.soapnotes.doctor.

Thank you so much!