Bird
0
0

Identify the error in this JWT guard snippet that causes it to always allow access even with invalid tokens:

medium📝 Debug Q14 of 15
NestJS - Guards
Identify the error in this JWT guard snippet that causes it to always allow access even with invalid tokens:
async canActivate(context: ExecutionContext) {
  const request = context.switchToHttp().getRequest();
  const token = request.headers['authorization']?.split(' ')[1];
  if (!token) return false;
  try {
    const payload = await this.jwtService.verifyAsync(token);
    request.user = payload;
  } catch {
    return true;
  }
  return true;
}
AThe method should not be async
BThe token extraction splits incorrectly
CThe catch block returns true, allowing access on token errors
DThe user is not attached to the request
Step-by-Step Solution
Solution:
  1. Step 1: Review the catch block behavior

    The catch block returns true, which means even if token verification fails, access is allowed.
  2. Step 2: Understand correct error handling in guards

    On verification failure, the guard should deny access by returning false or throwing an exception.
  3. Final Answer:

    The catch block returns true, allowing access on token errors -> Option C
  4. Quick Check:

    Catch returning true = always allow access [OK]
Quick Trick: Catch block must deny access, not allow it [OK]
Common Mistakes:
  • Returning true in catch block
  • Ignoring token verification errors
  • Not attaching user to request

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes