Bird
0
0

Given the following NestJS JWT guard code snippet, what will happen if the request has no Authorization header?

medium📝 component behavior Q13 of 15
NestJS - Guards
Given the following NestJS JWT guard code snippet, what will happen if the request has no Authorization header?
canActivate(context: ExecutionContext) {
  const request = context.switchToHttp().getRequest();
  const authHeader = request.headers['authorization'];
  if (!authHeader) {
    throw new UnauthorizedException('No token provided');
  }
  // further token validation...
  return true;
}
AThe guard allows the request to proceed
BThe guard throws an UnauthorizedException with message 'No token provided'
CThe guard returns false silently
DThe guard logs a warning but allows access
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the condition for missing Authorization header

    If the header is missing, the code throws UnauthorizedException with a specific message.
  2. Step 2: Understand the effect of throwing UnauthorizedException

    Throwing this exception stops the request and returns an HTTP 401 error to the client.
  3. Final Answer:

    The guard throws an UnauthorizedException with message 'No token provided' -> Option B
  4. Quick Check:

    No Authorization header = UnauthorizedException thrown [OK]
Quick Trick: Missing token causes UnauthorizedException throw [OK]
Common Mistakes:
  • Assuming guard returns false instead of throwing
  • Thinking request proceeds without token
  • Confusing logging with exception throwing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes