Complete the code to import the module needed for JWT in NestJS.
import { [1] } from '@nestjs/jwt';
The JwtModule is imported to configure JWT in NestJS.
Complete the code to register JwtModule with a secret key.
JwtModule.register({ secret: '[1]' })The secret key is usually named jwtSecret or similar to sign tokens.
Fix the error in the method that signs a refresh token with expiration.
async generateRefreshToken(userId: string) {
return this.jwtService.[1]({ userId }, { expiresIn: '7d' });
}The sign method is used to create tokens synchronously in NestJS JwtService.
Fill both blanks to create a refresh token validation guard.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; @Injectable() export class RefreshTokenGuard implements CanActivate { constructor(private readonly jwtService: JwtService) {} async canActivate(context: ExecutionContext): Promise<boolean> { const request = context.switchToHttp().getRequest(); const token = request.headers['[1]']; try { const payload = await this.jwtService.[2](token); return !!payload; } catch { return false; } } }
The refresh token is usually sent in the authorization header, and verify checks its validity.
Fill all three blanks to implement a refresh token service method that validates and issues a new access token.
async refreshTokens(refreshToken: string) {
const payload = await this.jwtService.[1](refreshToken);
if (!payload) throw new Error('Invalid token');
const userId = payload.[2];
const newAccessToken = await this.jwtService.[3]({ userId }, { expiresIn: '15m' });
return { accessToken: newAccessToken };
}First, verify checks the refresh token. Then, the userId is extracted from the payload. Finally, sign creates a new access token.