NestJS course ยท Module 4: Authentication
Two-Factor Authentication (2FA) - double guard of the Empire
In this lesson7
A legionary typed his password into a fake page pretending to be the fort's gate. From that moment the enemy knows it, and no amount of hashing in the database helps, because the attacker simply logs in. Architect Vitruvius decided to post a second guard at the gate, one who checks something entirely different from the password. That is how Two-Factor Authentication (2FA) works.
What is 2FA?
Two-Factor Authentication requires two independent verification factors:
- Something you know - the password (first factor)
- Something you have - a phone with a code-generating app (second factor)
The third category is "something you are", meaning biometrics. Even if the enemy intercepts a legionary's password, without the second factor he will not enter the fort!
TOTP - Time-based One-Time Password
TOTP (standard RFC 6238) derives a code from two ingredients: a shared secret and the current time. The phone and the server compute the same code independently, so the app works even offline:
// How TOTP works:
// 1. Server generates a random secret (key)
// 2. User scans the QR code with the secret in the authenticator app (Google Authenticator)
// 3. The app generates a 6-digit code every 30 seconds
// 4. Server verifies the code using the same secret and timeThe secret travels to the phone only once, inside the QR code. Beware of a common myth: a TOTP code is not single-use by itself. Within its time window it works a second time unless the server remembers that it has already accepted it.
Installing the libraries
You need two packages: otplib for the codes and qrcode for the image shown to the app:
# otplib (v13+) - TOTP and HOTP library
npm install otplib
# qrcode - generating QR codes
npm install qrcode
npm install -D @types/qrcodeVersion 13 of otplib (January 2026) rewrote the API from scratch. The authenticator object from version 12, which you will find in older tutorials, is gone, replaced by the functions generateSecret, generateURI and an asynchronous verify.
TwoFactor Service
The service starts with imports and configuration. We import generateSecret as generateTotpSecret so that it cannot be confused with the service's own method:
// auth/two-factor.service.ts
import { Injectable, UnauthorizedException, BadRequestException } from '@nestjs/common';
import { generateSecret as generateTotpSecret, generateURI, verify } from 'otplib';
import * as qrcode from 'qrcode';
import { randomInt } from 'node:crypto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
@Injectable()
export class TwoFactorService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
// TOTP configuration: 6 digits and a new code every 30 seconds are the otplib
// defaults; we accept a code from +/- 30 s, that is one step each way
private readonly totpOptions = { epochTolerance: 30 };epochTolerance: 30 is the equivalent of the old window: 1: the server also accepts the code from the previous and the next 30-second step, which forgives small clock differences.
Step one generates the secret and the QR code:
// Step 1: Generate secret and QR code
async generateSecret(userId: number): Promise<{
secret: string;
qrCodeUrl: string;
backupCodes: string[];
}> {
const user = await this.usersRepository.findOne({ where: { id: userId } });
if (!user) {
throw new BadRequestException('Legionary not found!');
}
if (user.twoFactorEnabled) {
throw new BadRequestException('2FA is already active!');
}
// Generate random secret
const secret = generateTotpSecret();
// Generate URI for the authenticator app
const otpauthUrl = generateURI({
issuer: 'Imperium Romanum', // Application name
label: user.email,
secret,
});
// Generate QR code as data URL
const qrCodeUrl = await qrcode.toDataURL(otpauthUrl);
// Generate backup codes
const backupCodes = this.generateBackupCodes(8);
// Save secret temporarily (don't activate yet!)
await this.usersRepository.update(userId, {
twoFactorSecret: secret,
twoFactorBackupCodes: JSON.stringify(
backupCodes.map(code => ({ code, used: false }))
),
});
return { secret, qrCodeUrl, backupCodes };
}generateURI() builds an otpauth://totp/... address, and qrcode.toDataURL() turns it into an image. We store the secret, but we do not enable 2FA yet. In production, encrypt the secret in the database and hash the backup codes like passwords.
Step two confirms that scanning worked:
// Step 2: Verify and activate 2FA
async enableTwoFactor(userId: number, code: string): Promise<boolean> {
const user = await this.usersRepository.findOne({ where: { id: userId } });
if (!user || !user.twoFactorSecret) {
throw new BadRequestException('Generate the secret first!');
}
// Verify the code from the app
const { valid } = await verify({
token: code,
secret: user.twoFactorSecret,
...this.totpOptions,
});
if (!valid) {
throw new UnauthorizedException('Invalid 2FA code!');
}
// Activate 2FA
await this.usersRepository.update(userId, {
twoFactorEnabled: true,
});
return true;
}Only a correct code from the app turns 2FA on. If scanning had failed, the legionary is not locked out of his own account.
Step three runs at every login:
// Step 3: Verify code during login
async verifyCode(userId: number, code: string): Promise<boolean> {
const user = await this.usersRepository.findOne({ where: { id: userId } });
if (!user || !user.twoFactorSecret) {
throw new UnauthorizedException('2FA is not configured!');
}
// Check if it's a backup code
if (code.length === 8) {
return this.verifyBackupCode(user, code);
}
// Verify TOTP code
const { valid } = await verify({
token: code,
secret: user.twoFactorSecret,
...this.totpOptions,
});
return valid;
}
// Backup code verification
private async verifyBackupCode(user: User, code: string): Promise<boolean> {
const backupCodes = JSON.parse(user.twoFactorBackupCodes || '[]');
const codeEntry = backupCodes.find(
(bc: any) => bc.code === code && !bc.used
);
if (!codeEntry) return false;
// Mark as used
codeEntry.used = true;
await this.usersRepository.update(user.id, {
twoFactorBackupCodes: JSON.stringify(backupCodes),
});
return true;
}An eight-character code is a backup code, marked as used once consumed, and a six-digit one goes to verify(). The result also carries a timeStep field: store it and pass it as afterTimeStep in the next verification, and the same code will not pass twice.
Finally, the backup codes and turning 2FA off:
// Generate backup codes
private generateBackupCodes(count: number): string[] {
const codes: string[] = [];
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (let i = 0; i < count; i++) {
let code = '';
for (let j = 0; j < 8; j++) {
code += chars.charAt(randomInt(chars.length));
}
codes.push(code);
}
return codes;
}
// Deactivate 2FA
async disableTwoFactor(userId: number, code: string): Promise<void> {
const isValid = await this.verifyCode(userId, code);
if (!isValid) {
throw new UnauthorizedException('Invalid code - cannot disable 2FA!');
}
await this.usersRepository.update(userId, {
twoFactorEnabled: false,
twoFactorSecret: null,
twoFactorBackupCodes: null,
});
}
}randomInt() from the node:crypto module uses a cryptographically secure random number generator. Math.random() is predictable and unfit for secrets. Disabling 2FA requires a valid code, so a hijacked session alone is not enough to remove the second guard.
2FA Controller
The controller exposes three routes, all behind a JwtAuthGuard set on the class:
// auth/two-factor.controller.ts
import { Controller, Post, Get, Body, UseGuards, Req } from '@nestjs/common';
import { TwoFactorService } from './two-factor.service';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
@Controller('auth/2fa')
@UseGuards(JwtAuthGuard)
export class TwoFactorController {
constructor(private twoFactorService: TwoFactorService) {}
// Step 1: Start 2FA configuration
@Post('setup')
async setup(@Req() req) {
const result = await this.twoFactorService.generateSecret(req.user.userId);
return {
message: 'Scan the QR code in the authenticator app',
qrCodeUrl: result.qrCodeUrl,
backupCodes: result.backupCodes,
warning: 'Save the backup codes in a safe place!',
};
}
// Step 2: Confirm configuration with a code from the app
@Post('verify')
async verify(@Req() req, @Body('code') code: string) {
await this.twoFactorService.enableTwoFactor(req.user.userId, code);
return {
message: '2FA has been activated! Double guard protects your account.',
enabled: true,
};
}
// Disable 2FA
@Post('disable')
async disable(@Req() req, @Body('code') code: string) {
await this.twoFactorService.disableTwoFactor(req.user.userId, code);
return {
message: '2FA has been deactivated.',
enabled: false,
};
}
}req.user.userId comes from JwtStrategy. setup returns the QR code and the backup codes only once, so the client app should ask the user to save them.
2FA Guard - guardian of the second gate
The guard lets a request through when 2FA is disabled or the session has already passed it:
// auth/guards/two-factor.guard.ts
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { UnauthorizedException } from '@nestjs/common';
import { TwoFactorService } from '../two-factor.service';
@Injectable()
export class TwoFactorGuard implements CanActivate {
constructor(private twoFactorService: TwoFactorService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const user = request.user;
// If 2FA is not enabled, let through
if (!user.twoFactorEnabled) {
return true;
}
// Check if the user already passed 2FA in this session
if (user.twoFactorVerified) {
return true;
}
throw new UnauthorizedException(
'2FA verification required! Enter the code from your authenticator app.'
);
}
}The trap: JwtStrategy from the JWT lesson returns only userId, username and role. Without the twoFactorEnabled and twoFactorVerified fields in req.user, the check !user.twoFactorEnabled is always true and the guard lets everyone in. Add both fields to the payload of the full token issued after a successful 2FA, and return them from validate().
Login flow with 2FA
The complete login process with 2FA looks like this:
- The legionary provides username + password (first factor)
- The server verifies the credentials and checks whether 2FA is active
- If so - it returns a temporary token and asks for the 2FA code
- The legionary opens the authenticator app and enters the 6-digit code
- The server verifies the TOTP code and issues a full access token
- The legionary has access to the fort!
// Example flow in AuthService
async loginWith2FA(loginDto: LoginDto): Promise<any> {
// Step 1: Verify password
const user = await this.validateUser(loginDto.username, loginDto.password);
if (!user) {
throw new UnauthorizedException('Invalid credentials!');
}
// Step 2: Check if 2FA is active
if (user.twoFactorEnabled) {
if (!loginDto.twoFactorCode) {
// Return a temporary token requiring 2FA, signed with a separate secret
// so that JwtAuthGuard never accepts it as a full access token
const tempToken = this.jwtService.sign(
{ sub: user.id, requiresTwoFactor: true },
{ secret: this.configService.get('JWT_2FA_SECRET'), expiresIn: '5m' },
);
return { requiresTwoFactor: true, tempToken };
}
// Step 3: Verify 2FA code
const is2FAValid = await this.twoFactorService.verifyCode(
user.id,
loginDto.twoFactorCode,
);
if (!is2FAValid) {
throw new UnauthorizedException('Invalid 2FA code!');
}
}
// Step 4: Issue full token
return this.generateTokenPair(user);
}We sign the temporary token with a separate secret, JWT_2FA_SECRET. If it shared the access token's secret, JwtAuthGuard would let its holder into protected routes and the second guard would have nothing to do. You know generateTokenPair() from the refresh tokens lesson. As a second factor, choose a TOTP app over SMS messages, which can be intercepted through SIM swapping - that is my recommendation.
In the next module you will carry JWT tokens over into WebSocket communication.
Remember: a single trick can steal a password, but the TOTP secret stays in the legionary's phone, so the enemy has to defeat two independent guards at once.
Code for this lesson: src/auth/two-factor.service.ts
// Two-Factor Authentication (2FA) w NestJS
import { Injectable, UnauthorizedException, BadRequestException } from '@nestjs/common';
import { authenticator } from 'otplib';
import * as qrcode from 'qrcode';
// ============================================
// 1. TwoFactorService - the heart of 2FA
// ============================================
@Injectable()
class TwoFactorService {
constructor() {
// TOTP configuration
authenticator.options = {
digits: 6, // 6-digit code
step: 30, // New code every 30 seconds
window: 1, // Tolerance +/- 1 step
};
}
// TODO: Implement secret generation
async generateSecret(userId: number, email: string) {
// TODO: Use authenticator.generateSecret()
const secret = authenticator.generateSecret();
// TODO: Generate URI for the authenticator app
const otpauthUrl = authenticator.keyuri(
email,
'Imperium Romanum',
secret,
);
// TODO: Generate a QR code
const qrCodeUrl = await qrcode.toDataURL(otpauthUrl);
// TODO: Generate backup codes
const backupCodes = this.generateBackupCodes(8);
return { secret, qrCodeUrl, backupCodes };
}
// TODO: Implement TOTP code verification
verifyCode(secret: string, code: string): boolean {
// TODO: Use authenticator.verify()
return authenticator.verify({
token: code,
secret: secret,
});
}
// Generating backup codes
private generateBackupCodes(count: number): string[] {
const codes: string[] = [];
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (let i = 0; i < count; i++) {
let code = '';
for (let j = 0; j < 8; j++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
codes.push(code);
}
return codes;
}
}
// ============================================
// 2. Demonstration of the 2FA flow
// ============================================
console.log('=== Two-Factor Authentication (2FA) ===');
console.log('');
console.log('Setup flow:');
console.log('1. POST /auth/2fa/setup -> QR code + backup codes');
console.log('2. User scans QR in Google Authenticator');
console.log('3. POST /auth/2fa/verify -> confirm with code from the app');
console.log('');
console.log('Login flow with 2FA:');
console.log('1. POST /auth/login -> { requiresTwoFactor: true, tempToken }');
console.log('2. POST /auth/2fa/authenticate -> full JWT token');
console.log('');
console.log('TOTP: Time-based One-Time Password');
console.log('The code changes every 30 seconds');
console.log('Backup codes: one-time backup codes');
Docs entries used in this lesson
Spotted a mistake in this lesson?