0
0
NestJSframework~10 mins

Role-based authorization in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Role-based authorization
User sends request with JWT token
Extract user roles from token
Check required roles for route
Compare user roles with required roles
Allow access
Send response
The system checks the user's roles from their token and compares them to the roles required by the route to decide access.
Execution Sample
NestJS
import { CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!requiredRoles) return true;

    const { user } = context.switchToHttp().getRequest();
    return requiredRoles.some(role => user.roles?.includes(role));
  }
}
This guard checks if the user has any of the roles required by the route to allow access.
Execution Table
StepActionData ExtractedCheckResult
1Request received with JWT tokenJWT token with roles ['user', 'admin']N/AProceed
2Extract roles from tokenUser roles: ['user', 'admin']N/AProceed
3Get required roles from route metadataRequired roles: ['admin']N/AProceed
4Compare user roles with required rolesUser roles: ['user', 'admin']Does user have 'admin'?Yes
5Allow accessN/AN/AAccess granted
6Send responseN/AN/AResponse sent
7If user lacked roleUser roles: ['user']Does user have 'admin'?No
8Deny accessN/AN/A403 Forbidden sent
💡 Execution stops after access is granted or denied based on role check.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
user.rolesundefined['user', 'admin']['user', 'admin']['user', 'admin']['user', 'admin']
requiredRolesundefinedundefined['admin']['admin']['admin']
accessAllowedundefinedundefinedundefinedtruetrue
Key Moments - 3 Insights
Why does the guard allow access if no roles are required on the route?
If requiredRoles is undefined (no roles set), the guard returns true immediately (see execution_table step 3), meaning open access.
What happens if the user has multiple roles but none match the required roles?
The guard checks all user roles against required roles (step 4). If none match, it returns false and denies access (steps 7-8).
How does the guard get the user's roles?
The guard extracts the user object from the request (step 2) and reads the roles array from it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what roles does the user have at step 2?
A['admin']
B['user', 'admin']
C['guest']
Dundefined
💡 Hint
Check the 'Data Extracted' column at step 2 in the execution_table.
At which step does the guard decide to deny access?
AStep 3
BStep 5
CStep 8
DStep 1
💡 Hint
Look for the step where '403 Forbidden sent' appears in the 'Result' column.
If the route had no required roles, what would the guard return?
Atrue
Bthrows error
Cfalse
Dundefined
💡 Hint
See the guard's behavior when requiredRoles is undefined in execution_table step 3.
Concept Snapshot
Role-based authorization in NestJS:
- Use a RolesGuard implementing CanActivate.
- Extract required roles from route metadata.
- Extract user roles from request.
- Allow access if user roles include any required role.
- Deny access with 403 if no match.
- If no roles required, allow access by default.
Full Transcript
Role-based authorization in NestJS works by checking the user's roles against roles required by a route. When a request arrives, the guard extracts the user's roles from the JWT token in the request. It then reads the required roles set on the route handler. If no roles are required, access is allowed immediately. Otherwise, the guard compares the user's roles with the required roles. If the user has at least one matching role, access is granted. If not, the guard denies access by sending a 403 Forbidden response. This process ensures only users with proper roles can access protected routes.