ProjectsSecurityAuthNode.js
Implement Secure OTP Authentication (2FA) in Node.js
3.17 min read
Md Nasim Sheikh
You've seen those 6-digit codes that change every 30 seconds. That is TOTP (Time-Based One-Time Password).
It's actually simple math based on a shared secret key and the current Unix Timestamp.
Advertisement
The Theory
- Server generates a random secret (Base32 string).
- User scans it into Google Authenticator (QR Code).
- Both Server and App calculate:
HMAC-SHA1(Secret, CurrentTime / 30). - If the result matches, the user is authenticated.
The Code
We use the otplib package.
npm install otplib qrcode
1. Generating the Secret (Registration)
const { authenticator } = require('otplib');
const qrcode = require('qrcode');
const secret = authenticator.generateSecret();
// Store 'secret' in your DB associated with the user!
const otpauth = authenticator.keyuri('user@email.com', 'MyAppName', secret);
qrcode.toDataURL(otpauth, (err, imageUrl) => {
// Send this Image URL to the frontend for the user to scan
});
2. Verifying the Token (Login)
const isValid = authenticator.check(userToken, userSecretFromDB);
if (isValid) {
console.log('Access Granted');
} else {
console.log('Access Denied');
}
Backup Codes
If a user loses their phone, they are locked out. You must generate a set of static "backup codes" (random strings) and save them during setup.
Advertisement
Quiz
Quick Quiz
Why doesn't the server need to communicate with the user's phone to verify the code?
Conclusion
Adding 2FA is the single biggest security upgrade you can offer users. Never roll your own crypto; use standard libraries like otplib.
Written by
Md Nasim Sheikh
Software Developer at softexForge
Verified Author150+ Projects
Published: