Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Implement role-based access control in a NestJS application using decorators and guards.

  1. User

    Implement role-based access control in a NestJS application using decorators and guards.

  2. GLM 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:

    1. User Model/Roles: We need a way to represent users and their roles.
    2. Decorator: A custom decorator to mark routes with required roles (e.g., @Roles('admin')).
    3. 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.
    4. 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:

    1. Setup: Create a basic NestJS project structure (mentally).
    2. Roles Enum: Define available roles (e.g., User, Admin).
    3. Custom Decorator (@Roles):
      • Use SetMetadata to attach role data to the handler/class.
    4. Authentication Context (Mocking):
      • Need an AuthGuard (usually JWT) that validates the token and attaches the user to the request object. I'll keep this brief but essential, as the RBAC guard needs request.user.
    5. 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.
    6. 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 Reflector to read metadata.
    • Handling "No Roles": If a route isn't decorated with @Roles, what happens? Usually, public routes need @Public() or the guard just returns true if 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 @Roles is 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 AuthGuard that hardcodes a user for demonstration purposes, or explain that JwtAuthGuard usually 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') populates req.user. The RolesGuard reads req.user. I should make sure the example shows @UseGuards(AuthGuard, RolesGuard). Order matters here!

    Structure of the response:

    1. Prerequisites: Mention the need for an Auth mechanism (JWT usually).
    2. Step 1: Define Roles.
    3. Step 2: Create the Decorator.
    4. Step 3: Create the Guard.
    5. Step 4: Applying to Controllers.
    6. 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 the RolesGuard. 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 user object to the request object.

    1. Define Roles

    First, define the roles available in your application. Using an enum is 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 SetMetadata function. 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:

    1. Is the user authenticated? (Does request.user exist?)
    2. Does the user possess at least one of the required roles defined in the decorator?

    Note: We inject Reflector to read the metadata set by the @Roles decorator.

    // 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 the RolesGuard (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

    1. Request Incoming: A user tries to GET /products/admin-only.
    2. AuthGuard: Runs first. Verifies the JWT token and attaches user (e.g., { id: 1, name: 'John', role: 'user' }) to the request.
    3. RolesGuard: Runs second.
      • Uses Reflector to read the metadata ['admin'] from the @Roles decorator.
      • Looks at request.user.role (which is 'user').
      • Compares 'user' against ['admin'].
      • Comparison fails -> Throws 403 Forbidden Exception.

    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
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.