How To Create A Two-Factor Authentication (2FA) In Node.js

Two-factor authentication (2FA) module in Node.js using the speakeasy and express packages:

Step 1: Install Required Packages Install the speakeasy and express packages, which provide the necessary functionality for 2FA in Node.js. You can install them using npm:

				
					npm install speakeasy express
				
			

Step 2: Implement the Two-Factor Authentication Logic Create a Node.js file, for example, twofactor.js, and implement the logic for generating and verifying 2FA tokens using the speakeasy package. Here’s an example:

				
					const express = require('express');
const speakeasy = require('speakeasy');

const app = express();
app.use(express.json());

// Generate a secret key and QR code for the user to scan
app.post('/generate', (req, res) => {
  const secret = speakeasy.generateSecret({ length: 20 });

  const otpAuthUrl = speakeasy.otpauthURL({
    secret: secret.base32,
    label: 'MyApp',
    algorithm: 'sha1',
    issuer: 'MyApp',
  });

  res.json({ secret: secret.base32, otpAuthUrl });
});

// Verify the user's 2FA token
app.post('/verify', (req, res) => {
  const { secret, token } = req.body;

  const verified = speakeasy.totp.verify({
    secret,
    encoding: 'base32',
    token,
  });

  if (verified) {
    res.json({ success: true, message: 'Token is valid.' });
  } else {
    res.status(401).json({ success: false, message: 'Token is invalid.' });
  }
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});
				
			

In this example, we define two routes: /generate for generating a secret key and QR code, and /verify for verifying the user’s 2FA token. The /generate route generates a secret key using speakeasy.generateSecret and creates an OTP authentication URL using speakeasy.otpauthURL. The /verify route verifies the user’s token using speakeasy.totp.verify.

Step 3: Run the Node.js Server Run the following command to start the Node.js server:

				
					node twofactor.js
				
			

The server will start listening on port 3000.

Step 4: Test the Two-Factor Authentication You can now test the two-factor authentication functionality using tools like Postman or by making HTTP requests programmatically. Here are the example requests you can send:

  • Generate Secret Key and QR Code:

    • Method: POST
    • URL: http://localhost:3000/generate
    • Body: Empty
    • Response: Secret key and OTP authentication URL
  • Verify 2FA Token:

    • Method: POST
    • URL: http://localhost:3000/verify
    • Body:
				
					{
  "secret": "<generated_secret_key>",
  "token": "<user_input_token>"
}
				
			
  • Response: Success or failure message

Please note that this is a basic example of a two-factor authentication module in Node.js using the speakeasy and express packages. You can further customize and enhance the module based on your specific requirements, such as integrating with a database to store user secrets, implementing user registration and login flows, or integrating with an authentication middleware in your Node.js application.