Implementing 2 Factor Authentication(2FA)

Implementing 2FA with Node.js and Authy

Rishikesh Dhokare
6 min readNov 17, 2019

Have you heard about 2 Factor Authentication? If yes, and want to know how to implement it, you are at the right place.

This post will demonstrate 2FA with Node.js and Authy in following steps —

  1. Create your API Key on Authy Dashboard
  2. Create a simple Node.js application
  3. Create Registration API
  4. Create Verification API

The complete source code of this application is available here.

1. Create your API Key on Authy Dashboard

To create your API key, you have to sign in to Authy Dashboard. Authy is a service provided by Twilio specifically for 2 Factor Authentication and a few more interesting things in this domain. You can read more about Authy and Twilio on their website.

You need few things before you can actually start writing the code. You either have to install Authy app on your mobile or provide your phone number while signing up so that they can send you a SMS before directing to the Authy dashboard.

You can either login with the authy credentials or with twilio account to which you have linked your authy account.

login to Authy with email and password or via signing in with Twilio
login to Authy with email and password or via signing in with Twilio

Once you do that, you will be asked to enter the Authy Token. If you have installed the Authy app, you will get a notification with the token in it. Alternatively you can request the token via SMS.

Enter Authy token
Enter Authy token

Assuming you are now an Authy user and logged in to your dashboard, use following steps to create an application.

  1. Click on “+ New Application” link at the bottom of the navigation panel.
  2. This will open up a dialog box. Let’s call our application “test-app”.
  3. This will take you to the API tutorial page. You can either start learning about how the Authy API works or go to your application dashboard. For the scope of this post, let’s go to the dashboard.
  4. Here you can see two keys — (a) API key for Production and (b) API key for Testing. For playing around and trying things out you can use the latter.
Authy API Keys
Authy API Keys

2. Create a simple Node.js application

Let’s quickly create a simple Node.js application.

  • Create a folder called 2fa-app and go to that folder from the terminal.
  • Run npm init -y. This will create a Node.js application skeleton(mainly package.json file). The -y option will answer yes to all the questions on the terminal.
create a simple node.js application
create a simple node.js application
  • Run npm install express body-parser authy — save command to install express, body-parser and authy. — save will save them to the package.json file.
Install dependencies
Install dependencies
  • Create a file from the terminal called app.js
create app.js
create app.js
  • Add following code to app.js
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');

var port = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use('/api', router);

router.get('/', function(req, res) {
res.json({ message: 'Hey there!' });
});

app.listen(port);
console.log('Server started on port - ' + port);
run app.js
api is up and running
api is up and running
  • Hurray! Now you have a node application is running with a simple API.

3. Create registration API

Add following code to app.js to create registration api. Replace ‘your-auth-key’ with the the API key we created in step #1.

var authy = require('authy')('your-auth-key');
router.get('/register', function(req, res) {
console.log('New register request...');
var isSuccessful = false;

var email = req.param('email');
var phone = req.param('phone');
var countryCode = req.param('countryCode');
authy.register_user(email, phone, countryCode, function (regErr, regRes) {
console.log('In Registration...');
if (regErr) {
console.log(regErr);
res.send('There was some error registering the user.');
} else if (regRes) {
console.log(regRes);
authy.request_sms(regRes.user.id, function (smsErr, smsRes) {
console.log('Requesting SMS...');
if (smsErr) {
console.log(smsErr);
res.send('There was some error sending OTP to cell phone.');
} else if (smsRes) {
console.log(smsRes);
res.send('OTP Sent to the cell phone.');
}
});
}
});
});

Let’s dig a little bit deeper in the code above. I am using Authy API client for Node.js to communicate with authy server. /register api takes 3 query parameters (1) email (2) phone number and (3) country code. You can use authy’s register_user function with all the three parameters and a callback function which takes error and response as parameters. In the function, if you receive any errors from authy, just print it and send a message — ‘There was some error registering the user.’ to the user.

If there are no errors, print the response you got from authy. Now, the interesting part is making authy send you a SMS for the verification purpose on your registered cell phone number. You can achieve this using request_sms function. It takes user Id (which you received from the response of register_user function) and a callback function with error and response. If you receive any errors while requesting SMS, just log it and send a message to user — ‘There was some error sending OTP to cell phone.’

If there are no errors, it means the SMS was successfully sent to your registered phone number. So, just send a message — ‘OTP Sent to the cell phone.’

Awesome! You have now called Authy API and requested for the registration.

4. Create verification API

The registration API sent you an OTP on your registered cell phone number. Now it’s time to verify the OTP. Let’s create an API for verification. Add following code to your app.js -

router.get('/verify', function(req, res) {
console.log('New verify request...');
var id = req.param('id');
var token = req.param('token');

authy.verify(id, token, function (verifyErr, verifyRes) {
console.log('In Verification...');
if (verifyErr) {
console.log(verifyErr);
res.send('OTP verification failed.');
} else if (verifyRes) {
console.log(verifyRes);
res.send('OTP Verified.');
}
})
});

All this API does is, takes two query parameters (1) user Id and (2) OTP sent via SMS. You can now use authy’s verify function with the user Id and OTP token and a callback function which takes error and response objects. If you get any errors while verification, just log it and send a message — ‘OTP verification failed.’

If there are no errors, that means the OTP verification was successful. So, send a message — ‘OTP Verified.’

Cool! You have just implemented 2 Factor Authentication using Node.js and Authy.

Once you start using the end to end application, you can see the registered users on the authy dashboard. I am attaching a screenshot of one of my applications.

registered users on Authy

Again, The complete source code of this application is available here.

If you found this useful, don’t forget to give as many claps as you can and follow :)

--

--

Rishikesh Dhokare

I am a Software Engineer from India and working in Berlin, Germany. I write about technology, my experiences in Germany, travel in Europe.