Implementing 2 Factor Authentication(2FA)

Implementing 2FA with Node.js and Authy

1. Create your API Key on Authy Dashboard

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
Enter Authy token
Enter Authy token
Authy API Keys
Authy API Keys

2. Create a simple Node.js application

create a simple node.js application
create a simple node.js application
Install dependencies
Install dependencies
create app.js
create 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

3. Create registration API

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.');
}
});
}
});
});

4. Create verification API

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.');
}
})
});
registered users on Authy

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
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.