0
0
NestJSframework~10 mins

Refresh token pattern in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the module needed for JWT in NestJS.

NestJS
import { [1] } from '@nestjs/jwt';
Drag options to blanks, or click blank then click option'
AJwtModule
BJwtGuard
CJwtStrategy
DJwtService
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing JwtService instead of JwtModule
Confusing JwtStrategy with JwtModule
2fill in blank
medium

Complete the code to register JwtModule with a secret key.

NestJS
JwtModule.register({ secret: '[1]' })
Drag options to blanks, or click blank then click option'
AjwtSecret
BrefreshSecret
CmySecretKey
DaccessSecret
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'mySecretKey' which is generic
Using 'refreshSecret' which is usually for refresh tokens
3fill in blank
hard

Fix the error in the method that signs a refresh token with expiration.

NestJS
async generateRefreshToken(userId: string) {
  return this.jwtService.[1]({ userId }, { expiresIn: '7d' });
}
Drag options to blanks, or click blank then click option'
AcreateToken
BsignAsync
CgenerateToken
Dsign
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent signAsync
Using non-existent methods like createToken
4fill in blank
hard

Fill both blanks to create a refresh token validation guard.

NestJS
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;
    }
  }
}
Drag options to blanks, or click blank then click option'
Aauthorization
Bverify
Crefresh-token
Ddecode
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'refresh-token' header which is uncommon
Using decode instead of verify causing no validation
5fill in blank
hard

Fill all three blanks to implement a refresh token service method that validates and issues a new access token.

NestJS
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 };
}
Drag options to blanks, or click blank then click option'
Averify
BuserId
Csign
Ddecode
Attempts:
3 left
💡 Hint
Common Mistakes
Using decode instead of verify causing no validation
Accessing wrong payload property
Using non-existent signAsync