0
0
NestJSframework~20 mins

Refresh token pattern in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Refresh Token Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a refresh token is expired in this NestJS service?
Consider this NestJS AuthService method that handles refresh tokens. What will be the result if the refresh token is expired?
NestJS
async refreshToken(userId: string, refreshToken: string) {
  const user = await this.userService.findById(userId);
  if (!user || user.refreshToken !== refreshToken) {
    throw new UnauthorizedException('Invalid refresh token');
  }
  try {
    const payload = this.jwtService.verify(refreshToken);
    const newAccessToken = this.jwtService.sign({ sub: userId });
    return { accessToken: newAccessToken };
  } catch (e) {
    throw new UnauthorizedException('Refresh token expired');
  }
}
AThe method returns a new access token ignoring the expired refresh token.
BThe method returns null without throwing an error.
CThe method throws UnauthorizedException with message 'Refresh token expired'.
DThe method throws a NotFoundException because the user is not found.
Attempts:
2 left
💡 Hint
Look at the try-catch block and what happens when jwtService.verify fails.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a NestJS guard to check refresh token validity?
You want to create a guard that checks if the refresh token in the request headers is valid. Which code snippet is syntactically correct and follows NestJS patterns?
A
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class RefreshTokenGuard {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const token = request.headers['refresh-token'];
    return token === 'valid-token';
  }
}
B
import { CanActivate, ExecutionContext } from '@nestjs/common';

export class RefreshTokenGuard implements CanActivate {
  canActivate(context: ExecutionContext) {
    const request = context.getRequest();
    const token = request.headers['refresh-token'];
    return token === 'valid-token';
  }
}
C
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class RefreshTokenGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const token = request.headers['refresh-token'];
    return token === 'valid-token';
  }
}
D
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class RefreshTokenGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const token = request.headers['refresh-token'];
    return token === 'valid-token';
  }
}
Attempts:
2 left
💡 Hint
Check for correct decorator usage and method signatures.
state_output
advanced
2:00remaining
What is the output of this refresh token service method after multiple calls?
Given this simplified NestJS AuthService snippet, what will be the value of user.refreshToken after calling refreshToken twice with the same initial refresh token?
NestJS
class AuthService {
  constructor(private userService) {}

  async refreshToken(userId, refreshToken) {
    const user = await this.userService.findById(userId);
    if (!user || user.refreshToken !== refreshToken) {
      throw new Error('Invalid refresh token');
    }
    const newRefreshToken = 'new-token-' + Math.random();
    user.refreshToken = newRefreshToken;
    await this.userService.update(userId, { refreshToken: newRefreshToken });
    return { accessToken: 'access-token', refreshToken: newRefreshToken };
  }
}

// Initial user.refreshToken = 'initial-token'

// Call 1: refreshToken(userId, 'initial-token')
// Call 2: refreshToken(userId, 'initial-token')
AThe second call throws an error because the refresh token no longer matches the stored one.
BThe second call returns a new refresh token and updates user.refreshToken again.
CThe second call returns the same refresh token as the first call without error.
DThe second call returns null because the refresh token is invalid.
Attempts:
2 left
💡 Hint
Think about how the stored refresh token changes after the first call.
🔧 Debug
advanced
2:00remaining
Why does this NestJS refresh token validation always fail?
Look at this code snippet from a NestJS AuthService. The refresh token validation always fails even with a correct token. What is the bug?
NestJS
async validateRefreshToken(userId: string, token: string) {
  const user = await this.userService.findById(userId);
  if (!user) return false;
  try {
    this.jwtService.verify(token, { secret: process.env.JWT_SECRET });
  } catch {
    return false;
  }
  return user.refreshToken === token;
}
AThe secret used in verify is incorrect, so tokens never validate.
BjwtService.verify throws an error on invalid token but is used as a boolean, causing unhandled exceptions.
CThe method should compare user.refreshToken before calling jwtService.verify.
DThe method returns false because user.refreshToken is undefined.
Attempts:
2 left
💡 Hint
Check how jwtService.verify behaves on invalid tokens.
🧠 Conceptual
expert
2:00remaining
Which statement best describes the security benefit of rotating refresh tokens in NestJS?
In a NestJS app implementing refresh token rotation, what is the main security advantage of issuing a new refresh token on each refresh request?
AIt limits the window for token theft by invalidating old refresh tokens after use.
BIt allows multiple devices to share the same refresh token safely.
CIt eliminates the need for access tokens entirely.
DIt reduces server load by caching refresh tokens longer.
Attempts:
2 left
💡 Hint
Think about what happens if a refresh token is stolen and rotation is used.