Complete the code to import PassportModule in a NestJS module.
import { Module } from '@nestjs/common'; import { PassportModule } from '[1]'; @Module({ imports: [PassportModule.register({ defaultStrategy: 'jwt' })], }) export class AuthModule {}
PassportModule is imported from @nestjs/passport to integrate Passport.js with NestJS.
Complete the code to create a JWT strategy class extending PassportStrategy.
import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; @Injectable() export class JwtStrategy extends PassportStrategy([1]) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secretKey', }); } async validate(payload: any) { return { userId: payload.sub, username: payload.username }; } }
The PassportStrategy function is called with the Strategy from passport-jwt to create a JWT strategy.
Fix the error in the AuthGuard usage to protect a route with JWT strategy.
import { Controller, Get, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller('profile') export class ProfileController { @Get() @UseGuards([1]('jwt')) getProfile() { return { message: 'This is a protected route' }; } }
The AuthGuard from @nestjs/passport is used with the strategy name 'jwt' to protect routes.
Fill both blanks to register PassportModule and JwtStrategy in the AuthModule.
import { Module } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { JwtStrategy } from './jwt.strategy'; @Module({ imports: [[1].register({ defaultStrategy: 'jwt' })], providers: [[2]], exports: [[1]], }) export class AuthModule {}
The PassportModule is registered with the default strategy, and JwtStrategy is provided to enable JWT authentication.
Fill all three blanks to create a login route that uses AuthService to validate user and issue JWT.
import { Controller, Post, Body } from '@nestjs/common'; import { AuthService } from './auth.service'; @Controller('auth') export class AuthController { constructor(private readonly authService: [1]) {} @Post('login') async login(@Body() [2]: any) { return this.authService.[3]([2].username, [2].password); } }
The controller injects AuthService, receives a login DTO object, and calls validateUser method to check credentials and return a JWT.