Implement role-based access control in a NestJS application using decorators and guards.
- User
Implement role-based access control in a NestJS application using decorators and guards.
Assistant
The user wants to know how to implement Role-Based Access Control (RBAC) in a NestJS application. The request specifies using "decorators and guards".
Key components needed:
- User Model/Roles: We need a way to represent users and their roles.
- Decorator: A custom decorator to mark routes with required roles (e.g.,
@Roles('admin')). - Guard: A guard to intercept requests, check if the user is authenticated, and then check if their role matches the required roles defined by the decorator.
- Authentication: RBAC depends on knowing who the user is. I should mention or mock a basic Authentication mechanism (like a JWT guard) because the RBAC guard usually runs after authentication.
Step-by-Step Implementation Plan:
- Setup: Create a basic NestJS project structure (mentally).
- Roles Enum: Define available roles (e.g.,
User,Admin). - Custom Decorator (
@Roles):- Use
SetMetadatato attach role data to the handler/class.
- Use
- Authentication Context (Mocking):
- Need an
AuthGuard(usually JWT) that validates the token and attaches the user to therequestobject. I'll keep this brief but essential, as the RBAC guard needsrequest.user.
- Need an
- RBAC Guard (
RolesGuard):- Implement
CanActivate. - Reflect the metadata to get required roles.
- Get the current user from the request.
- Compare user role vs. required roles.
- Implement
- Usage Example:
- Apply the guards and decorator to a controller.
Refining the details:
- Decorator:
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);This is the standard pattern. - Guard: Needs to inject
Reflectorto read metadata. - Handling "No Roles": If a route isn't decorated with
@Roles, what happens? Usually, public routes need@Public()or the guard just returnstrueif no roles are defined. I will implement the logic where if no roles are required, access is granted (allowing public routes), or assume an AuthGuard handles the distinction. Let's stick to the strict interpretation: If@Rolesis present, validate it. If not, pass (or rely on the AuthGuard). - Auth Guard: I shouldn't write a full JWT implementation because that complicates the answer, but I must show how the user gets onto the request. I'll create a dummy
AuthGuardthat hardcodes a user for demonstration purposes, or explain thatJwtAuthGuardusually precedes this.
Drafting the Code:
- roles.enum.ts: Standard enum.
- roles.decorator.ts:
SetMetadata. - roles.guard.ts: The core logic.
reflector.get,request.user. - Controller:
@UseGuards(AuthGuard, RolesGuard),@Roles(Role.Admin).
Self-Correction/Edge Cases:
- What if the user has multiple roles? The logic should usually be "has at least one of the required roles" or "has all". The standard "has some" is easier and most common. I'll stick to
some(). - How to combine with Passport/JWT? The
AuthGuard('jwt')populatesreq.user. TheRolesGuardreadsreq.user. I should make sure the example shows@UseGuards(AuthGuard, RolesGuard). Order matters here!
Structure of the response:
- Prerequisites: Mention the need for an Auth mechanism (JWT usually).
- Step 1: Define Roles.
- Step 2: Create the Decorator.
- Step 3: Create the Guard.
- Step 4: Applying to Controllers.
- Bonus/Best Practice: Handling Public routes (optional but helpful).
Let's write the code mentally.
Guard Logic:
@Injectable() export class RolesGuard implements CanActivate { constructor(private reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [ context.getHandler(), context.getClass(), ]); if (!requiredRoles) return true; // No roles required const { user } = context.switchToHttp().getRequest(); return requiredRoles.some((role) => user.roles?.includes(role)); } }Looks solid.
Decorator Logic:
export const ROLES_KEY = 'roles'; export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);Standard.
Controller:
@UseGuards(AuthGuard, RolesGuard) // Order is important! @Get('admin-data') @Roles('admin') getAdminData() {}I will present this clearly with file structures.
Final Polish: Make sure to emphasize that the
AuthGuard(or whatever puts the user on the request) must run before theRolesGuard. NestJS executes guards in order.Let's generate the response. To implement Role-Based Access Control (RBAC) in NestJS, you need to combine two main components: a Custom Decorator (to attach metadata to routes) and a Guard (to check that metadata against the user's permissions).
Here is a step-by-step implementation guide.
Prerequisites
This guide assumes you already have an authentication mechanism (like JWT) that attaches a
userobject to therequestobject.1. Define Roles
First, define the roles available in your application. Using an
enumis best practice to avoid typos.// roles/roles.enum.ts export enum Role { User = 'user', Admin = 'admin', Moderator = 'moderator', }2. Create the Decorator
We need a decorator to assign specific roles to a controller or a route handler. We will use NestJS's
SetMetadatafunction. This attaches the role data to the route's metadata, which the Guard can read later.// roles/roles.decorator.ts import { SetMetadata } from '@nestjs/common'; import { Role } from './roles.enum'; export const ROLES_KEY = 'roles'; export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);3. Create the Roles Guard
The Guard is the logic gate. It runs before the route handler. It performs two checks:
- Is the user authenticated? (Does
request.userexist?) - Does the user possess at least one of the required roles defined in the decorator?
Note: We inject
Reflectorto read the metadata set by the@Rolesdecorator.// roles/roles.guard.ts import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { Role } from './roles.enum'; import { ROLES_KEY } from './roles.decorator'; @Injectable() export class RolesGuard implements CanActivate { constructor(private reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { // 1. Retrieve the roles required for this route from the metadata const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [ context.getHandler(), // Method level context.getClass(), // Class level ]); // If no roles are required, allow access (or return false if you want strict default) if (!requiredRoles) { return true; } // 2. Get the user from the request object // (This assumes you have an AuthGuard that runs before this and populates request.user) const { user } = context.switchToHttp().getRequest(); if (!user) { throw new ForbiddenException('User not authenticated'); } // 3. Check if the user's role matches any of the required roles const hasRole = requiredRoles.some((role) => user.role?.includes(role)); if (!hasRole) { throw new ForbiddenException('You do not have permission (Forbidden)'); } return true; } }4. Implementation in a Controller
Now, apply the guard and the decorator to your routes. Note that order matters: The
AuthGuard(authentication) must come before theRolesGuard(authorization).// app.controller.ts import { Controller, Get, UseGuards } from '@nestjs/common'; import { AuthGuard } from './auth/auth.guard'; // Your existing Auth Guard import { Roles } from './roles/roles.decorator'; import { RolesGuard } from './roles/roles.guard'; import { Role } from './roles/roles.enum'; @Controller('products') // Apply Guards globally to the controller (optional) or per method @UseGuards(AuthGuard, RolesGuard) export class AppController { @Get() @Roles(Role.User, Role.Admin) // Users AND Admins can access findAll() { return 'This is visible to Users and Admins'; } @Get('admin-only') @Roles(Role.Admin) // Only Admins can access getAdminData() { return 'This is sensitive admin data'; } }Summary of How It Works
- Request Incoming: A user tries to
GET /products/admin-only. - AuthGuard: Runs first. Verifies the JWT token and attaches
user(e.g.,{ id: 1, name: 'John', role: 'user' }) to the request. - RolesGuard: Runs second.
- Uses
Reflectorto read the metadata['admin']from the@Rolesdecorator. - Looks at
request.user.role(which is'user'). - Compares
'user'against['admin']. - Comparison fails -> Throws
403 Forbidden Exception.
- Uses
Handling Multiple Roles
If your application allows a user to have multiple roles (e.g., an array
roles: ['admin', 'editor']), update the check logic in the Guard:// Inside RolesGuard... const hasRole = requiredRoles.some((role) => user.roles?.includes(role)); // Note the change from user.role to user.roles
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.