Bird
Raised Fist0
NestJSframework~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of role-based authorization in a NestJS application?
easy
A. To handle HTTP request parsing
B. To manage database connections
C. To control access to routes based on user roles
D. To format response data

Solution

  1. Step 1: Understand role-based authorization concept

    Role-based authorization restricts access to parts of an app depending on the user's role.
  2. Step 2: Identify the purpose in NestJS context

    In NestJS, it controls which users can access certain routes or features based on their roles.
  3. Final Answer:

    To control access to routes based on user roles -> Option C
  4. Quick Check:

    Role-based authorization = Access control by roles [OK]
Hint: Remember: roles decide who can access what [OK]
Common Mistakes:
  • Confusing authorization with authentication
  • Thinking it manages database or HTTP parsing
  • Mixing up roles with user data formatting
2. Which decorator is commonly used in NestJS to specify roles allowed on a route?
easy
A. @Roles()
B. @UseGuards()
C. @Controller()
D. @Get()

Solution

  1. Step 1: Identify role-specifying decorators

    In NestJS, @Roles() decorator marks which roles can access a route.
  2. Step 2: Differentiate from other decorators

    @UseGuards() applies guards, @Controller() defines controllers, @Get() defines HTTP GET routes.
  3. Final Answer:

    @Roles() -> Option A
  4. Quick Check:

    @Roles() sets allowed roles [OK]
Hint: Look for decorator naming roles directly [OK]
Common Mistakes:
  • Using @UseGuards() to specify roles directly
  • Confusing route decorators with role decorators
  • Missing that @Roles() is custom, not built-in
3. Given this code snippet, what will happen when a user with role 'user' accesses the route?
@Roles('admin')
@Get('admin-data')
getAdminData() {
  return 'Secret admin data';
}
medium
A. The user will receive 'Secret admin data'
B. The user will get a 403 Forbidden error
C. The route will return undefined
D. The server will crash with an error

Solution

  1. Step 1: Check the role required by the route

    The route requires 'admin' role via @Roles('admin').
  2. Step 2: Compare with user's role

    User has role 'user', which does not match 'admin'.
  3. Final Answer:

    The user will get a 403 Forbidden error -> Option B
  4. Quick Check:

    Role mismatch causes 403 Forbidden [OK]
Hint: If user role ≠ required role, access denied [OK]
Common Mistakes:
  • Assuming any role can access
  • Thinking route returns undefined on denial
  • Expecting server crash on role mismatch
4. Identify the error in this NestJS guard code for role checking:
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  const user = request.user;
  const roles = this.reflector.get('roles', context.getHandler());
  if (!roles) {
    return true;
  }
  return roles.includes(user.role);
}
medium
A. Missing async keyword on canActivate
B. Returning true when roles are not defined
C. Using getHandler() instead of getClass() for roles
D. Not checking if user exists before accessing user.role

Solution

  1. Step 1: Review user role access

    The code accesses user.role without verifying if user is defined.
  2. Step 2: Identify potential runtime error

    If user is undefined, accessing user.role causes an error.
  3. Final Answer:

    Not checking if user exists before accessing user.role -> Option D
  4. Quick Check:

    Always check user before role access [OK]
Hint: Check user object exists before role check [OK]
Common Mistakes:
  • Assuming user is always present
  • Confusing getHandler() and getClass() usage
  • Thinking async is required for synchronous guard
5. How can you combine role-based authorization with route-level guards to allow access only if the user has either 'admin' or 'manager' role in NestJS?
hard
A. Use @Roles('admin', 'manager') decorator and a RolesGuard that checks for any matching role
B. Use two separate @Roles decorators, one for 'admin' and one for 'manager', on the same route
C. Use @UseGuards(AdminGuard, ManagerGuard) without @Roles decorator
D. Check roles manually inside the controller method without decorators or guards

Solution

  1. Step 1: Understand role decorator usage

    @Roles() accepts multiple roles to allow any of them access.
  2. Step 2: Use a guard that checks if user role matches any allowed role

    The RolesGuard reads roles from metadata and checks if user role is included.
  3. Final Answer:

    Use @Roles('admin', 'manager') decorator and a RolesGuard that checks for any matching role -> Option A
  4. Quick Check:

    Multiple roles in @Roles() + guard = flexible access [OK]
Hint: Pass multiple roles in one @Roles() decorator [OK]
Common Mistakes:
  • Using multiple @Roles decorators on one route
  • Applying multiple guards instead of one flexible guard
  • Skipping decorators and guards for manual checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard