Bird
Raised Fist0
NestJSframework~20 mins

Role-based authorization in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Role-based Authorization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this NestJS guard when a user with role 'user' accesses an admin route?

Consider this NestJS guard that checks if the user has the 'admin' role:

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    return user?.roles?.includes('admin');
  }
}

If a request has user.roles = ['user'], what will the guard return?

Afalse
Btrue
Cthrows an error
Dundefined
Attempts:
2 left
💡 Hint

Check if the roles array includes 'admin'.

📝 Syntax
intermediate
2:00remaining
Which option correctly applies a RolesGuard to a NestJS controller route?

Given a RolesGuard and a Roles decorator, which code snippet correctly protects the getAdminData route to only allow 'admin' role users?

A
@Get('admin')
@UseGuards(RolesGuard)
@Roles('admin')
getAdminData() { return 'secret'; }
B
@Roles('admin')
@UseGuards(RolesGuard)
@Get('admin')
getAdminData() { return 'secret'; }
C
@UseGuards(RolesGuard)
@Roles('admin')
@Get('admin')
getAdminData() { return 'secret'; }
D
@Get('admin')
@Roles('admin')
@UseGuards(RolesGuard)
getAdminData() { return 'secret'; }
Attempts:
2 left
💡 Hint

Order of decorators matters: guards should be applied before roles.

🔧 Debug
advanced
2:00remaining
Why does this RolesGuard always deny access even for 'admin' users?

Look at this RolesGuard code:

canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  const user = request.user;
  const requiredRoles = this.reflector.get('roles', context.getHandler());
  return requiredRoles.some(role => user.roles.includes(role));
}

Even when the user has the 'admin' role and the route requires 'admin', access is denied. Why?

ArequiredRoles is undefined
Bthis.reflector is undefined or not injected
Cuser.roles is undefined
Dsome() returns false if user.roles is empty
Attempts:
2 left
💡 Hint

Check if this.reflector is properly set up.

❓ state_output
advanced
2:00remaining
What is the value of 'isAuthorized' after this NestJS guard runs?

Given this guard snippet:

canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  const user = request.user;
  const roles = ['admin', 'editor'];
  const isAuthorized = roles.some(role => user.roles?.includes(role));
  return isAuthorized;
}

If user.roles = ['viewer', 'editor'], what is the value of isAuthorized?

Afalse
Bthrows an error
Cundefined
Dtrue
Attempts:
2 left
💡 Hint

Check if any role in ['admin', 'editor'] is in user.roles.

🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of the Reflector in NestJS role-based authorization?

In NestJS, the Reflector class is often used in guards for role-based authorization. What is its main purpose?

AIt retrieves metadata set by decorators on route handlers or controllers.
BIt manages user session data during authorization.
CIt encrypts role information before checking access.
DIt automatically injects user roles into the request object.
Attempts:
2 left
💡 Hint

Think about how decorators store information in NestJS.

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