Search⌘ K

Implementing Role-Based Authorization

Explore how to implement role-based authorization in NestJS applications by creating an AccessControlGuard, using the Roles decorator, and managing user roles with JWT. This lesson helps you control access to routes based on user roles like admin or viewer, ensuring secure backend operations.

Defining AccessControlGuard

After understanding how to retrieve metadata, we pass it to the Roles decorator. Let’s create a dedicated AccessControlGuard responsible for access control in the guards folder.

TypeScript 4.9.5
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Role } from 'src/auth/entities/user.entity';
@Injectable()
export class AccessControlGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.getAllAndOverride<Role[]>('roles', [
context.getHandler(),
context.getClass(),
]);
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
return roles.includes(user.role);
}
}

Here is the breakdown of our implementation in the canActivate method:

  • Lines 10–13: The method uses this.reflector.getAllAndOverride(...) to retrieve the role specified in the @Roles decorator at either the controller or method level. For example, if we apply @Roles(Role.Admin) to a method within a controller, the result of this.reflector.getAllAndOverride('...') will be an array (['admin']) containing the authorized roles for accessing these routes .

  • Lines 15–17: If ...