Bird
Raised Fist0
NestJSframework~20 mins

JWT authentication guard in NestJS - Practice Problems & Coding Challenges

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

Practice

(1/5)
1. What is the main purpose of a JWT authentication guard in a NestJS application?
easy
A. To verify the JWT token and protect routes from unauthorized access
B. To generate new JWT tokens for users
C. To store user data in the database
D. To handle HTTP request logging

Solution

  1. Step 1: Understand the role of JWT guard

    The JWT authentication guard checks if the incoming request has a valid JWT token.
  2. Step 2: Identify what the guard protects

    The guard protects routes by allowing access only if the token is valid, preventing unauthorized users.
  3. Final Answer:

    To verify the JWT token and protect routes from unauthorized access -> Option A
  4. Quick Check:

    JWT guard = verify token and protect routes [OK]
Hint: JWT guard checks token validity to protect routes [OK]
Common Mistakes:
  • Confusing guard with token generation
  • Thinking guard stores user data
  • Assuming guard handles logging
2. Which of the following is the correct way to apply a JWT authentication guard to a controller route in NestJS?
easy
A. Use @Get('jwt') decorator on the route
B. @Controller('jwt') before the class
C. Inject JwtService directly in the route handler
D. @UseGuards(AuthGuard('jwt')) before the route handler method

Solution

  1. Step 1: Recall how guards are applied in NestJS

    Guards are applied using the @UseGuards() decorator before route handlers or controllers.
  2. Step 2: Identify the correct guard usage for JWT

    The JWT guard is used as AuthGuard('jwt') inside @UseGuards decorator.
  3. Final Answer:

    @UseGuards(AuthGuard('jwt')) before the route handler method -> Option D
  4. Quick Check:

    @UseGuards(AuthGuard('jwt')) = correct syntax [OK]
Hint: Use @UseGuards(AuthGuard('jwt')) to protect routes [OK]
Common Mistakes:
  • Using @Controller('jwt') instead of guard
  • Injecting JwtService instead of using guard
  • Confusing route decorators with guards
3. 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;
}
medium
A. The guard allows the request to proceed
B. The guard throws an UnauthorizedException with message 'No token provided'
C. The guard returns false silently
D. The guard logs a warning but allows access

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]
Hint: 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
4. 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;
}
medium
A. The method should not be async
B. The token extraction splits incorrectly
C. The catch block returns true, allowing access on token errors
D. The user is not attached to the request

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]
Hint: 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
5. You want to create a custom JWT authentication guard that extracts the user from the token and adds a custom property isAdmin based on the user's role. Which approach correctly extends the default JWT guard to achieve this?
hard
A. Extend AuthGuard('jwt'), override handleRequest to add isAdmin to user, then return user
B. Create a new guard without extending AuthGuard and manually decode token
C. Use a middleware instead of a guard to add isAdmin property
D. Override canActivate to return true always and add isAdmin in controller

Solution

  1. Step 1: Understand extending AuthGuard('jwt')

    Extending the default JWT guard allows reuse of token validation logic.
  2. Step 2: Override handleRequest to customize user object

    handleRequest receives the validated user; adding isAdmin here modifies the user before passing it on.
  3. Step 3: Return the modified user to allow access

    Returning the user with isAdmin set ensures the controller can access this property safely.
  4. Final Answer:

    Extend AuthGuard('jwt'), override handleRequest to add isAdmin to user, then return user -> Option A
  5. Quick Check:

    Extend guard + override handleRequest = customize user [OK]
Hint: Extend AuthGuard and override handleRequest to customize user [OK]
Common Mistakes:
  • Not extending AuthGuard and duplicating logic
  • Using middleware instead of guard for auth
  • Overriding canActivate incorrectly
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