Building an Authentication layer is really common among all kinds of apps these days. But suppose you were building a trading app, maybe another app related to financial markets. You will really have to consider additional security for your users.
That's where 2 Factor authentication comes into play.
According to Wikipedia, two-factor authentication means:
Multi-factor authentication is an electronic authentication method in which a computer user is granted access to a website or application only after successfully presenting two or more pieces of evidence to an authentication mechanism.
Okay enough talk, let's build a small Node.js Module with 2Factor Auth using Google Authenticator
Assumptions: You already have basic knowledge of Node.js and a base Node.js project setup.
Install dependencies
For the sake of this project, we will use a module called speakeasy to handle all the core parts of 2-factor auth like generating and verifying tokens. We will also use bluebird to convert our code into promises.
Execute the following commands in your terminal
yarn add bluebird speakeasy
Finally, some code.
Now we will write helper functions to generate and verify 2-factor auth secrets.
Generate secret
const speakeasy = require("speakeasy");
const Promise = require("bluebird");
exports.generateSecret = () => {
return new Promise((resolve, reject) => {
resolve(speakeasy.generateSecret({ length: 20 }));
});
};
Verify secret
exports.verifySecret = (secret, token) => {
/*Secret is generated by speakeasy in above function*/
/*token is a numeric code found in Google Auth app*/
return new Promise((resolve, reject) => {
resolve(
speakeasy.totp.verify({
secret,
token,
encoding: "base32",
})
);
});
};
generateSecret function returns a base32 secret, that you can use as a QR code for the user to scan.
Now you can just use these helper functions in your controllers like the below example:
Generate a 2F Auth Secret key for new user
module.exports.generateKey = (req, res) => {
secretKeyHelper
.generateSecret()
.then((secret) => {
return res.status(200).send({
message: "secret for 2f auth",
base32: secret.base32,
otpAuthUrl: secret.otpauth_url,
});
})
.catch((error) => {
return res.status(500).send({ ErrorOccured: error });
});
};
Verify a 2F Auth Secret key for the user
module.exports.verifyToken = (req, res) => {
secretKeyHelper
.verifySecret(req.body.secretKey, req.body.token)
.then((tokenVerifyResult) => {
return res
.status(200)
.send({
message: "Token Verification result",
result: tokenVerifyResult,
});
})
.catch((error) => {
return res.status(500).send({ ErrorOccured: error });
});
};
So using these simple lines of code, we created our 2-factor authentication module in Node.js. Ping me if you need help with your project.