17. Two-Factor Authentication (2FA)
Passwords alone are no longer sufficient. If a password is stolen, an attacker can log in immediately. Two-Factor Authentication (2FA) adds a second verification layer, requiring something the user HAS in addition to something they KNOW.
The Three Authentication Factors
Something you KNOW (password, PIN) + Something you HAVE (phone, hardware key) + Something you ARE (fingerprint, face). 2FA uses any two of these.
What is TOTP?
TOTP (Time-based One-Time Password) is the most common 2FA method. Authenticator apps like Google Authenticator, Authy, or Microsoft Authenticator generate 6-digit codes that change every 30 seconds.
How TOTP Works: 1. Server generates a secret key (shared secret) 2. User scans QR code with authenticator app 3. App stores the secret 4. App generates codes using: code = HMAC-SHA1(secret, current time / 30) 5. Server generates the same code using the stored secret 6. If codes match, 2FA is successful
Step 1: Install Required Packages
We need two packages: speakeasy for TOTP generation/verification and qrcode to generate QR codes for the authenticator app.
npm install speakeasy qrcode
Step 2: Generate a 2FA Secret
When a user wants to enable 2FA, we generate a unique secret key for them. This secret is what the authenticator app will store. We also generate a QR code URL that the user will scan.
const speakeasy = require('speakeasy'); function generate2FASecret(userEmail) { const secret = speakeasy.generateSecret({ name: `MyApp:${userEmail}`, issuer: 'MyApp' }); return { secret: secret.base32, otpauthUrl: secret.otpauth_url }; } // Example const { secret, otpauthUrl } = generate2FASecret('alice@example.com'); console.log('Secret:', secret); console.log('OTPAuth URL:', otpauthUrl);
Step 3: Generate QR Code
The user cannot type the secret easily. We generate a QR code that the authenticator app can scan. This makes setup seamless.
const QRCode = require('qrcode'); async function getQRCodeDataURL(otpauthUrl) { // Generate QR code as a data URL (base64 image) return await QRCode.toDataURL(otpauthUrl); } // Example usage const qrCode = await getQRCodeDataURL(otpauthUrl); console.log(qrCode); // data:image/png;base64,iVBORw0KGgo...
Step 4: Enable 2FA Endpoint
This endpoint generates the secret and QR code, then temporarily stores the secret for verification. The secret is not permanently saved until the user verifies the code.
const speakeasy = require('speakeasy'); const QRCode = require('qrcode'); app.post('/api/2fa/enable', requireAuth, async (req, res) => { // 1. Generate secret and QR code const secret = speakeasy.generateSecret({ name: `MyApp:${req.user.email}`, issuer: 'MyApp' }); const qrCode = await QRCode.toDataURL(secret.otpauth_url); // 2. Store secret temporarily (Redis with 10 min TTL) await redis.setex(`2fa_setup:${req.user.id}`, 600, secret.base32); // 3. Send QR code and secret to frontend res.json({ qrCode: qrCode, secret: secret.base32 }); });
Step 5: Verify the 2FA Code
After scanning the QR code, the user enters the 6-digit code from their authenticator app. We verify it using the temporarily stored secret.
function verifyTOTP(secret, userToken) { return speakeasy.totp.verify({ secret: secret, encoding: 'base32', token: userToken, window: 1 // Allow 1 step before/after (30 seconds tolerance) }); } app.post('/api/2fa/verify', requireAuth, async (req, res) => { const { token } = req.body; // 1. Get the temporary secret from Redis const tempSecret = await redis.get(`2fa_setup:${req.user.id}`); if (!tempSecret) { return res.status(400).json({ error: '2FA setup expired. Please try again.' }); } // 2. Verify the code const isValid = verifyTOTP(tempSecret, token); if (!isValid) { return res.status(400).json({ error: 'Invalid verification code' }); } // 3. Save the secret permanently to the database await db.users.updateOne( { _id: req.user.id }, { $set: { twoFactorSecret: tempSecret, twoFactorEnabled: true } } ); // 4. Clean up temporary storage await redis.del(`2fa_setup:${req.user.id}`); res.json({ success: true, message: '2FA enabled successfully' }); });
window: 1 allows codes from 30 seconds before or after. This accounts for slight time differences between devices.Step 6: Login with 2FA (First Step)
When a user logs in with 2FA enabled, we first verify their password. If correct, we return a temporary token indicating 2FA is required.
app.post('/api/login', async (req, res) => { const { email, password } = req.body; // 1. Verify password const user = await authenticateUser(email, password); if (!user) { return res.status(401).json({ error: 'Invalid credentials' }); } // 2. Check if 2FA is enabled if (user.twoFactorEnabled) { // Generate a short-lived temporary token for 2FA step const tempToken = jwt.sign( { userId: user.id, purpose: '2fa' }, TEMP_SECRET, { expiresIn: '5m' } ); return res.json({ requires2FA: true, tempToken: tempToken }); } // 3. No 2FA, issue full access token const accessToken = jwt.sign({ userId: user.id }, JWT_SECRET); res.json({ accessToken }); });
Step 7: Verify 2FA During Login
The user now enters the 6-digit code from their authenticator app. We verify it and issue the final access token.
app.post('/api/login/2fa', async (req, res) => { const { tempToken, token } = req.body; // 1. Validate the temporary token let userId; try { const decoded = jwt.verify(tempToken, TEMP_SECRET); if (decoded.purpose !== '2fa') { throw new Error('Invalid token purpose'); } userId = decoded.userId; } catch (error) { return res.status(401).json({ error: 'Session expired. Please log in again.' }); } // 2. Get user and their 2FA secret const user = await db.users.findById(userId); if (!user || !user.twoFactorEnabled) { return res.status(400).json({ error: '2FA not enabled for this account' }); } // 3. Verify the TOTP code const isValid = speakeasy.totp.verify({ secret: user.twoFactorSecret, encoding: 'base32', token: token, window: 1 }); if (!isValid) { return res.status(401).json({ error: 'Invalid 2FA code' }); } // 4. Issue final access token const accessToken = jwt.sign({ userId: user.id }, JWT_SECRET); res.json({ accessToken }); });
Step 8: Recovery Codes
What happens if a user loses their phone? Without recovery codes, they would be permanently locked out. We generate 10 one-time use recovery codes during 2FA setup.
const crypto = require('crypto'); function generateRecoveryCodes() { const codes = []; for (let i = 0; i < 10; i++) { // Generate 8-character alphanumeric code const code = crypto.randomBytes(4).toString('hex').toUpperCase(); codes.push(code); } return codes; } // During 2FA setup, also generate recovery codes app.post('/api/2fa/enable', requireAuth, async (req, res) => { const secret = speakeasy.generateSecret({ name: `MyApp:${req.user.email}`, issuer: 'MyApp' }); const recoveryCodes = generateRecoveryCodes(); // Hash recovery codes before storing const hashedCodes = recoveryCodes.map(code => crypto.createHash('sha256').update(code).digest('hex') ); // Store secret AND hashed recovery codes temporarily await redis.setex(`2fa_setup:${req.user.id}`, 600, { secret: secret.base32, recoveryCodes: hashedCodes }); const qrCode = await QRCode.toDataURL(secret.otpauth_url); res.json({ qrCode: qrCode, secret: secret.base32, recoveryCodes: recoveryCodes // Show ONCE to user }); });
Step 9: Login with Recovery Code
If a user loses their phone, they can use a recovery code instead of the TOTP code. Each recovery code can be used only once.
app.post('/api/login/recovery', async (req, res) => { const { email, recoveryCode } = req.body; // 1. Find user const user = await db.users.findOne({ email }); if (!user) { return res.status(401).json({ error: 'Invalid credentials' }); } // 2. Hash the provided recovery code const hashedCode = crypto.createHash('sha256') .update(recoveryCode.toUpperCase()) .digest('hex'); // 3. Check if code exists and is not used if (!user.recoveryCodes.includes(hashedCode)) { return res.status(401).json({ error: 'Invalid recovery code' }); } // 4. Remove the used recovery code await db.users.updateOne( { _id: user.id }, { $pull: { recoveryCodes: hashedCode } } ); // 5. Issue access token const accessToken = jwt.sign({ userId: user.id }, JWT_SECRET); res.json({ accessToken }); });
Complete 2FA Flow Summary
Setup Phase: 1. User enables 2FA in settings 2. Server generates secret and QR code 3. User scans QR code with authenticator app 4. User enters 6-digit code to verify 5. Server saves secret and recovery codes Login Phase: 1. User enters email and password 2. Server verifies password 3. If 2FA enabled, server returns temporary token 4. User enters 6-digit code from authenticator app 5. Server verifies code and issues access token Recovery Phase: 1. User selects "Lost my phone" 2. User enters recovery code 3. Server verifies and consumes recovery code 4. User is logged in 5. User should generate new recovery codes
Knowledge Check
Ready to test your understanding of 17. Two-Factor Authentication (2FA)?