A JWT authentication guard helps protect parts of your app by checking if a user has a valid token before allowing access.
JWT authentication guard in 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 token = this.extractTokenFromHeader(request); if (!token) return false; try { const payload = this.jwtService.verify(token); request.user = payload; return true; } catch { return false; } } private extractTokenFromHeader(request: any): string | null { const authHeader = request.headers['authorization']; if (!authHeader) return null; const [type, token] = authHeader.split(' '); return type === 'Bearer' ? token : null; } }
The guard implements CanActivate to decide if a request can continue.
It extracts the JWT from the Authorization header and verifies it.
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) return false;
try {
const payload = this.jwtService.verify(token);
request.user = payload;
return true;
} catch {
return false;
}
}private extractTokenFromHeader(request: any): string | null {
const authHeader = request.headers['authorization'];
if (!authHeader) return null;
const [type, token] = authHeader.split(' ');
return type === 'Bearer' ? token : null;
}This example shows a simple controller with a route protected by the JWT guard. Only requests with a valid JWT can access the profile data.
import { Controller, Get, UseGuards, Req } from '@nestjs/common'; import { JwtAuthGuard } from './jwt-auth.guard'; @Controller('profile') export class ProfileController { @UseGuards(JwtAuthGuard) @Get() getProfile(@Req() request: any) { return { message: 'User profile data', user: request.user }; } } // JwtAuthGuard code as shown in syntax section
Always send the JWT in the Authorization header as Bearer <token>.
Make sure to handle token expiration and errors gracefully in your app.
Use HTTPS to keep tokens safe during transmission.
JWT authentication guards protect routes by verifying tokens.
They check the Authorization header for a valid Bearer token.
When valid, the guard allows access and attaches user info to the request.
Practice
Solution
Step 1: Understand the role of JWT guard
The JWT authentication guard checks if the incoming request has a valid JWT token.Step 2: Identify what the guard protects
The guard protects routes by allowing access only if the token is valid, preventing unauthorized users.Final Answer:
To verify the JWT token and protect routes from unauthorized access -> Option AQuick Check:
JWT guard = verify token and protect routes [OK]
- Confusing guard with token generation
- Thinking guard stores user data
- Assuming guard handles logging
Solution
Step 1: Recall how guards are applied in NestJS
Guards are applied using the @UseGuards() decorator before route handlers or controllers.Step 2: Identify the correct guard usage for JWT
The JWT guard is used as AuthGuard('jwt') inside @UseGuards decorator.Final Answer:
@UseGuards(AuthGuard('jwt')) before the route handler method -> Option DQuick Check:
@UseGuards(AuthGuard('jwt')) = correct syntax [OK]
- Using @Controller('jwt') instead of guard
- Injecting JwtService instead of using guard
- Confusing route decorators with guards
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;
}Solution
Step 1: Analyze the condition for missing Authorization header
If the header is missing, the code throws UnauthorizedException with a specific message.Step 2: Understand the effect of throwing UnauthorizedException
Throwing this exception stops the request and returns an HTTP 401 error to the client.Final Answer:
The guard throws an UnauthorizedException with message 'No token provided' -> Option BQuick Check:
No Authorization header = UnauthorizedException thrown [OK]
- Assuming guard returns false instead of throwing
- Thinking request proceeds without token
- Confusing logging with exception throwing
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;
}Solution
Step 1: Review the catch block behavior
The catch block returns true, which means even if token verification fails, access is allowed.Step 2: Understand correct error handling in guards
On verification failure, the guard should deny access by returning false or throwing an exception.Final Answer:
The catch block returns true, allowing access on token errors -> Option CQuick Check:
Catch returning true = always allow access [OK]
- Returning true in catch block
- Ignoring token verification errors
- Not attaching user to request
isAdmin based on the user's role. Which approach correctly extends the default JWT guard to achieve this?Solution
Step 1: Understand extending AuthGuard('jwt')
Extending the default JWT guard allows reuse of token validation logic.Step 2: Override handleRequest to customize user object
handleRequest receives the validated user; adding isAdmin here modifies the user before passing it on.Step 3: Return the modified user to allow access
Returning the user with isAdmin set ensures the controller can access this property safely.Final Answer:
Extend AuthGuard('jwt'), override handleRequest to add isAdmin to user, then return user -> Option AQuick Check:
Extend guard + override handleRequest = customize user [OK]
- Not extending AuthGuard and duplicating logic
- Using middleware instead of guard for auth
- Overriding canActivate incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
