Ensuring complete snippets
I need to make sure to provide enough detail for the implementer without being overly lengthy. I’ll want to include full snippets for roles.enum.ts, roles.decorator.ts, roles.guard.ts, and auth/jwt-auth.guard.ts as an optional part. Additionally, I should show usage in the controller and the global configuration in app.module.ts. It’s important to respond clearly and fully without unnecessary flattery so that the user gets the right information. Here’s a straightforward way to implement role-based access control (RBAC) in a NestJS app using decorators and guards.
1. Define your roles
Create a simple enum for roles, e.g. roles.enum.ts:
// src/auth/roles.enum.ts
export enum Role {
User = 'user',
Admin = 'admin',
Moderator = 'moderator',
}
Your User entity (or whatever you use for users) should expose roles, for example:
// src/users/user.entity.ts
import { Role } from '../auth/roles.enum';
export class User {
id: number;
email: string;
// e.g. ['user'] or ['admin', 'user']
roles: Role[];
}
2. Create a @Roles() decorator
Use SetMetadata to attach required roles to route handlers:
// src/auth/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);
Usage example:
@Roles(Role.Admin)
@Get('admin-only')
getAdminData() { ... }
3. Implement the RolesGuard
The guard reads metadata from the handler/class and compares it with the current user’s roles.
// src/auth/roles.guard.ts
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from './roles.decorator';
import { Role } from './roles.enum';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
// Get roles defined via @Roles() on handler or controller
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
// If no roles metadata, allow access (just an authenticated route, or public
// depending on how you combine with auth guards)
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
if (!user) {
throw new ForbiddenException('User not found in request');
}
const userRoles: Role[] = user.roles || [];
const hasRole = requiredRoles.some((role) => userRoles.includes(role));
if (!hasRole) {
throw new ForbiddenException('Insufficient role');
}
return true;
}
}
Assumption: your authentication process (e.g. JWT) attaches a user object to request.
4. Use with an authentication guard
Usually you’ll combine the RolesGuard with an auth guard (JWT, session, etc.).
Example using a JWT auth guard from @nestjs/passport:
// src/auth/jwt-auth.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
Then apply guards at the controller or route level:
// src/some/some.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { Roles } from '../auth/roles.decorator';
import { Role } from '../auth/roles.enum';
@Controller('admin')
@UseGuards(JwtAuthGuard, RolesGuard)
export class AdminController {
@Get()
@Roles(Role.Admin)
getAdminDashboard() {
return { message: 'Admin dashboard' };
}
@Get('moderation')
@Roles(Role.Admin, Role.Moderator)
getModerationPanel() {
return { message: 'Moderation panel' };
}
}
5. Optionally register guards globally
If you want all routes to be protected by JWT + roles automatically:
// src/app.module.ts
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
import { RolesGuard } from './auth/roles.guard';
@Module({
// imports, controllers, etc.
providers: [
{
provide: APP_GUARD,
useClass: JwtAuthGuard, // runs first
},
{
provide: APP_GUARD,
useClass: RolesGuard, // runs after JWT guard
},
],
})
export class AppModule {}
Now:
- Routes without
@Roles() will just require authentication.
- Routes with
@Roles() will require specific roles.
6. Example end-to-end flow
- Client sends JWT in
Authorization: Bearer <token>.
JwtAuthGuard validates token, attaches user to request.
RolesGuard:
- Reads
@Roles() metadata.
- Checks
request.user.roles against required roles.
- Allows or rejects with
ForbiddenException.
This pattern is the standard NestJS way to implement RBAC using decorators and guards. If you share how you’re currently authenticating (JWT, sessions, etc.), I can adapt the guard to match your setup.