QA
Beginner LevelAuthentication & Authorization

How does Two-Factor Authentication (2FA) using TOTP (Time-based One-Time Passwords) work?

❓ Interview Prompt: Explain multi-factor authentication factors, HMAC-based OTP algorithm (RFC 6238), QR code shared secrets, and 30-second time windows.

Multi-Factor Authentication (MFA) requires users to present two or more distinct authentication factors:

1
Knowledge Factor: Something you know (Password, PIN).
2
Possession Factor: Something you have (Authenticator App, Hardware Token, Phone).
3
Inherence Factor: Something you are (Fingerprint, FaceID).

How TOTP (Time-Based One-Time Password - RFC 6238) Works:

1
Setup: Server generates a cryptographically random Secret Seed Key displayed to the user as a QR Code ('otpauth://totp/...').
2
Sync: User scans the QR code into an Authenticator App (Google Authenticator, 1Password).
3
Calculation: Both client app and server calculate matching 6-digit codes every 30 seconds using HMAC-SHA1 over the current Unix timestamp:

$$\text{TOTP} = \text{Truncate}(\text{HMAC-SHA1}(\text{Secret}, \lfloor \text{CurrentTimestamp} / 30 \rfloor))$$

Code Implementation Example

typescript
import { generateSecret, verifyToken } from 'node-2fa';

// 1. Generate 2FA Secret Key & QR Code URL for setup
const secret = generateSecret({ name: 'MyApp', account: 'user@example.com' });
console.log('Secret Key:', secret.secret);
console.log('QR Code URL:', secret.qr);

// 2. Verify submitted 6-digit code during login
const isTokenValid = verifyToken(secret.secret, '540192'); // Returns delta offset if valid
💡Generating TOTP 2FA secret keys and verifying dynamic 6-digit codes.
🎯 Interview Key Takeaway

TOTP 2FA computes matching 6-digit codes every 30 seconds using a shared secret key and current Unix timestamp.

More Authentication & Authorization Interview Questions

Beginner LevelAuthentication & Authorization

Compare JWT Token Authentication versus Stateful Sessions, and explain OAuth 2.0 PKCE flow.

Beginner LevelAuthentication & Authorization

What is the fundamental difference between Authentication (AuthN) and Authorization (AuthZ)?

Beginner LevelAuthentication & Authorization

Why should passwords never be stored in plain text and how do bcrypt and Argon2id work?