ProjectsSecurityAuthNode.js

Implement Secure OTP Authentication (2FA) in Node.js

3.17 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

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

  1. Server generates a random secret (Base32 string).
  2. User scans it into Google Authenticator (QR Code).
  3. Both Server and App calculate: HMAC-SHA1(Secret, CurrentTime / 30).
  4. 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.

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like