Implement Two Factor Authentication (2FA) With Node JS Using Speakeasy

In this post, I want to explain about Implementation of Two Factor Authentication with Node.js.

Two Factor Authentication became more important nowadays for security purposes, Most of the sites which handle money or anything related to payment using two-factor authentication to make sure they are having right authenticated users on their website.

Here we are going to look into two-factor authentication implementation of Node.js using speakeasy.

Speakeasy is a one-time passcode generator, ideal for use in two-factor authentication, that supports Google Authenticator and other two-factor devices.

As it states, It is a one-time passcode generator and we should send that passcode to the user via email or SMS. When the user enters the passcode using speakeasy we can validate the one-time password and if password matches we can validate the user. Speakeasy makes implementation of two-factor authentication easy one.

This blog post will help anyone who wants to enable two-factor authentication in their application.

Node.js Implementation of SpeakEasy

First, You need to save speakeasy node package into your application and in node we can use npm.

npm install –save speakeasy

The package will get installed in your node module directory. Next step will be including it in your node application.

Now, One-time password token got generated and now you can send the token to the corresponding mobile number or through the email.

In the application standpoint, You should not store the token generated instead store the 30-digit secret key, in this case, we can alter the size of secret key based on your application need. Store the secret key against the user id in your application database.