Complete the code to import the module that helps with authentication in NestJS.
import { [1] } from '@nestjs/passport';
The PassportModule is the official NestJS module to handle authentication strategies.
Complete the code to protect a route using the AuthGuard in NestJS.
@UseGuards([1]('jwt')) @Get('profile') getProfile() { return 'User profile data'; }
The AuthGuard with 'jwt' strategy protects routes by checking the JWT token.
Fix the error in the JWT strategy validate method to correctly return the user object.
async validate(payload: any) {
const user = await this.userService.findById(payload.sub);
if (!user) {
throw new UnauthorizedException();
}
return [1];
}The validate method must return the full user object so it can be attached to the request.
Fill both blanks to create a JWT token with a secret and expiration time.
const token = this.jwtService.sign(payload, { secret: [1], expiresIn: [2] });The secret is a string used to sign the token, and expiresIn sets how long the token is valid.
Fill all three blanks to create a NestJS guard that extracts the JWT token from the request header.
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const authHeader = request.headers['[1]'];
if (!authHeader) return false;
const token = authHeader.split('[2]')[1];
return this.jwtService.verify(token, { secret: '[3]' });
}The JWT token is usually sent in the authorization header as 'Bearer <token>'. The guard splits the string by space and verifies the token with the secret.