0
0
NestJSframework~20 mins

JWT authentication guard in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
JWT Guard Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a valid JWT is provided to the guard?

Consider a NestJS JWT authentication guard that validates the token and attaches the user to the request. What is the expected behavior when a valid JWT is sent in the Authorization header?

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

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const authHeader = request.headers['authorization'];
    if (!authHeader) return false;
    const token = authHeader.split(' ')[1];
    try {
      const payload = this.jwtService.verify(token);
      request.user = payload;
      return true;
    } catch {
      return false;
    }
  }
}
AThe guard returns true but does not modify the request object.
BThe guard returns false and throws an exception.
CThe guard ignores the token and always returns true.
DThe guard returns true and attaches the decoded user payload to request.user.
Attempts:
2 left
💡 Hint

Think about what the guard does after verifying the token.

📝 Syntax
intermediate
2:00remaining
Which option correctly extracts the JWT from the Authorization header?

In a NestJS guard, you want to extract the JWT token from the Authorization header which looks like 'Bearer <token>'. Which code snippet correctly extracts the token?

Aconst token = request.headers['authorization'].replace('Bearer ', '');
Bconst token = request.headers['authorization'].split(' ')[1];
Cconst token = request.headers['authorization'].slice(7);
Dconst token = request.headers['authorization'].substring(7);
Attempts:
2 left
💡 Hint

Remember the 'Bearer ' prefix is 7 characters including the space.

🔧 Debug
advanced
2:00remaining
Why does this JWT guard always reject requests?

Given the following guard code, why does it always return false even with a valid token?

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

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const authHeader = request.headers['authorization'];
    if (!authHeader) return false;
    const token = authHeader.split(' ')[1];
    try {
      this.jwtService.verify(token);
      return false;
    } catch {
      return false;
    }
  }
}
AThe guard returns false after verifying the token instead of true.
BThe token extraction is incorrect causing verify to fail.
CThe JwtService is not injected properly causing an error.
DThe guard does not check for the Authorization header.
Attempts:
2 left
💡 Hint

Look at what the guard returns after successful verification.

state_output
advanced
2:00remaining
What is the value of request.user after a valid JWT is verified?

Assuming the JWT payload is {"sub": "123", "username": "alice"}, what will request.user contain after the guard runs successfully?

NestJS
const payload = { sub: '123', username: 'alice' };
request.user = payload;
A{"sub": "123", "username": "alice"}
B{"userId": "123", "name": "alice"}
Cnull
Dundefined
Attempts:
2 left
💡 Hint

The guard sets request.user to the decoded token payload.

🧠 Conceptual
expert
2:00remaining
What error occurs if the JWT token is missing in the Authorization header?

In a NestJS JWT guard, if the Authorization header is missing or does not contain a token, what error or behavior should you expect?

NestJS
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  const authHeader = request.headers['authorization'];
  if (!authHeader) return false;
  const token = authHeader.split(' ')[1];
  try {
    this.jwtService.verify(token);
    return true;
  } catch {
    return false;
  }
}
AThe guard throws a JwtMalformedError from the JwtService.
BThe guard throws a SyntaxError due to missing token.
CThe guard returns false and the request is denied without throwing an error.
DThe guard returns true and allows the request.
Attempts:
2 left
💡 Hint

Check the guard's behavior when the header is missing.