Skip to contentSkip to navigationSkip to topbar
Rate this Page:

Authy Two-factor Authentication Node.js Quickstart


(warning)

Warning

As of November 2022, Twilio no longer provides support for Authy SMS/Voice-only customers. Customers who were also using Authy TOTP or Push prior to March 1, 2023 are still supported. The Authy API is now closed to new customers and will be fully deprecated in the future.

For new development, we encourage you to use the Verify v2 API.

Existing customers will not be impacted at this time until Authy API has reached End of Life. For more information about migration, see Migrating from Authy to Verify for SMS(link takes you to an external page).

Adding two-factor authentication to your application is the easiest way to increase security and trust in your product without unnecessarily burdening your users. This quickstart guides you through building a Node.js(link takes you to an external page), AngularJS(link takes you to an external page), and MongoDB(link takes you to an external page) application that restricts access to a URL. Four Authy API channels are demoed: SMS, Voice, Soft Tokens and Push Notifications.

Ready to protect your toy app's users from nefarious balaclava wearing hackers? Dive in!


Sign Into - or Sign Up For - a Twilio Account

sign-into---or-sign-up-for---a-twilio-account page anchor

Create a new Twilio account (you can sign up for a free Twilio trial), or sign into an existing Twilio account(link takes you to an external page).

Create a New Authy Application

create-a-new-authy-application page anchor

Once logged in, visit the Authy Console(link takes you to an external page). Click on the red 'Create New Aplication' (or big red plus ('+') if you already created one) to create a new Authy application then name it something memorable.

Authy create new application.

You'll automatically be transported to the Settings page next. Click the eyeball icon to reveal your Production API Key.

Account Security API Key.

Copy your Production API Key to a safe place, you will use it during application setup.


Install and Launch MongoDB

install-and-launch-mongodb page anchor

When a user registers with your application, a request is made to Twilio to add that user to your App, and a user_id is returned. In this demo, we'll store the returned user_id in a MongoDB database.

Instructions for installing MongoDB vary by platform. Follow the instructions you need to install locally.

After installing, launch MongoDB. For *NIX and OSX, this may be as easy as:


_10
mongod


Setup Authy on Your Device

setup-authy-on-your-device page anchor

This two-factor authentication demos two channels which require an installed Authy app to test: Soft tokens and push authentications. While SMS and voice channels will work without the client, to try out all four authentication channels download and install the Authy app for Desktop or Mobile:


Clone and Setup the Application

clone-and-setup-the-application page anchor

Clone our Node.js repository locally(link takes you to an external page), then enter the directory. Install all of the necessary node modules:


_10
npm install

Next, open the file .env.example. There, edit the ACCOUNT_SECURITY_API_KEY, pasting in the API Key from the above step (in the console), and save the file as .env.

Depending on your system, you need to set the environmental variables before you continue. On *NIX, you can run:


_10
source .env

On Windows, depending on your shell, you will have to use SET.

Alternatively, you could use a package such as autoenv(link takes you to an external page) to load it at startup.

Add Your Application API Key

add-your-application-api-key page anchor

Enter the API Key from the Account Security console and optionally change the port.


_10
export ACCOUNT_SECURITY_API_KEY='ENTER_SECRET_HERE'
_10
export PORT=1337

Once you have added your API Key, you are ready to run! Launch Node with:


_10
node .

If MongoDB is running and your API Key is correct, you should get a message your new app is running!


Try the Node.js Two-Factor Demo

try-the-nodejs-two-factor-demo page anchor

With your phone (optionally with the Authy client installed) nearby, open a new browser tab and navigate to http://localhost:1337/register/(link takes you to an external page)

Enter your information and invent a password, then hit 'Register'. Your information is passed to Twilio (you will be able to see your user immediately in the console(link takes you to an external page)), and the application is returned a user_id.

Now visit http://localhost:1337/login/(link takes you to an external page) and login. You'll be presented with a happy screen:

Token Verification Page.

If your phone has the Authy app installed, you can immediately enter a soft token from the client to Verify. Additionally, you can try a push authentication simply by pushing the labeled button.

If you do not have the Authy app installed, the SMS and voice channels will also work in providing a token. To try different channels, you can logout to start the process again.

Two-Factor Authentication Channels

two-factor-authentication-channels page anchor

Demonstrating SMS, Voice, and Push Notification Two-Factor channels. (Soft Tokens can be entered directly.)


_440
var crypto = require('crypto');
_440
var mongoose = require('mongoose');
_440
var User = mongoose.model('User');
_440
var config = require('../config.js');
_440
var qs = require('qs');
_440
var request = require('request');
_440
var phoneReg = require('../lib/phone_verification')(config.API_KEY);
_440
_440
// https://github.com/seegno/authy-client
_440
const Client = require('authy-client').Client;
_440
const authy = new Client({key: config.API_KEY});
_440
_440
_440
function hashPW(pwd) {
_440
return crypto.createHash('sha256').update(pwd).digest('base64').toString();
_440
}
_440
_440
/**
_440
* Login a user
_440
* @param req
_440
* @param res
_440
*/
_440
exports.login = function (req, res) {
_440
User.findOne({username: req.body.username})
_440
.exec(function (err, user) {
_440
if (!user) {
_440
err = 'Username Not Found';
_440
} else if (('password' in req.body) && (user.hashed_password !==
_440
hashPW(req.body.password.toString()))) {
_440
err = 'Wrong Password';
_440
} else {
_440
createSession(req, res, user);
_440
}
_440
_440
if (err) {
_440
res.status(500).json(err);
_440
}
_440
});
_440
};
_440
_440
/**
_440
* Logout a user
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.logout = function (req, res) {
_440
req.session.destroy(function (err) {
_440
if (err) {
_440
console.log("Error Logging Out: ", err);
_440
return next(err);
_440
}
_440
res.status(200).send();
_440
});
_440
};
_440
_440
/**
_440
* Checks to see if the user is logged in and redirects appropriately
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.loggedIn = function (req, res) {
_440
if (req.session.loggedIn && req.session.authy) {
_440
res.status(200).json({url: "/protected"});
_440
} else if (req.session.loggedIn && !req.session.authy) {
_440
res.status(200).json({url: "/2fa"});
_440
} else {
_440
res.status(409).send();
_440
}
_440
};
_440
_440
/**
_440
* Sign up a new user.
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.register = function (req, res) {
_440
_440
var username = req.body.username;
_440
User.findOne({username: username}).exec(function (err, user) {
_440
if (err) {
_440
console.log('Rregistration Error', err);
_440
res.status(500).json(err);
_440
return;
_440
}
_440
if (user) {
_440
res.status(409).json({err: "Username Already Registered"});
_440
return;
_440
}
_440
_440
user = new User({username: req.body.username});
_440
_440
user.set('hashed_password', hashPW(req.body.password));
_440
user.set('email', req.body.email);
_440
user.set('authyId', null);
_440
user.save(function (err) {
_440
if (err) {
_440
console.log('Error Creating User', err);
_440
res.status(500).json(err);
_440
} else {
_440
_440
authy.registerUser({
_440
countryCode: req.body.country_code,
_440
email: req.body.email,
_440
phone: req.body.phone_number
_440
}, function (err, regRes) {
_440
if (err) {
_440
console.log('Error Registering User with Authy');
_440
res.status(500).json(err);
_440
return;
_440
}
_440
_440
user.set('authyId', regRes.user.id);
_440
_440
// Save the AuthyID into the database then request an SMS
_440
user.save(function (err) {
_440
if (err) {
_440
console.log('error saving user in authyId registration ', err);
_440
res.session.error = err;
_440
res.status(500).json(err);
_440
} else {
_440
createSession(req, res, user);
_440
}
_440
});
_440
});
_440
}
_440
});
_440
});
_440
};
_440
_440
_440
/**
_440
* Check user login status. Redirect appropriately.
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.loggedIn = function (req, res) {
_440
_440
if (req.session.loggedIn && req.session.authy) {
_440
res.status(200).json({url: "/protected"});
_440
} else if (req.session.loggedIn && !req.session.authy) {
_440
res.status(200).json({url: "/2fa"});
_440
} else {
_440
res.status(200).json({url: "/login"});
_440
}
_440
};
_440
_440
/**
_440
* Request a OneCode via SMS
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.sms = function (req, res) {
_440
var username = req.session.username;
_440
User.findOne({username: username}).exec(function (err, user) {
_440
console.log("Send SMS");
_440
if (err) {
_440
console.log('SendSMS', err);
_440
res.status(500).json(err);
_440
return;
_440
}
_440
_440
/**
_440
* If the user has the Authy app installed, it'll send a text
_440
* to open the Authy app to the TOTP token for this particular app.
_440
*
_440
* Passing force: true forces an SMS send.
_440
*/
_440
authy.requestSms({authyId: user.authyId}, {force: true}, function (err, smsRes) {
_440
if (err) {
_440
console.log('ERROR requestSms', err);
_440
res.status(500).json(err);
_440
return;
_440
}
_440
console.log("requestSMS response: ", smsRes);
_440
res.status(200).json(smsRes);
_440
});
_440
_440
});
_440
};
_440
_440
/**
_440
* Request a OneCode via a voice call
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.voice = function (req, res) {
_440
var username = req.session.username;
_440
User.findOne({username: username}).exec(function (err, user) {
_440
console.log("Send SMS");
_440
if (err) {
_440
console.log('ERROR SendSMS', err);
_440
res.status(500).json(err);
_440
return;
_440
}
_440
_440
/**
_440
* If the user has the Authy app installed, it'll send a text
_440
* to open the Authy app to the TOTP token for this particular app.
_440
*
_440
* Passing force: true forces an voice call to be made
_440
*/
_440
authy.requestCall({authyId: user.authyId}, {force: true}, function (err, callRes) {
_440
if (err) {
_440
console.error('ERROR requestcall', err);
_440
res.status(500).json(err);
_440
return;
_440
}
_440
console.log("requestCall response: ", callRes);
_440
res.status(200).json(callRes);
_440
});
_440
});
_440
};
_440
_440
/**
_440
* Verify an Authy Token
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.verify = function (req, res) {
_440
var username = req.session.username;
_440
User.findOne({username: username}).exec(function (err, user) {
_440
console.log("Verify Token");
_440
if (err) {
_440
console.error('Verify Token User Error: ', err);
_440
res.status(500).json(err);
_440
}
_440
authy.verifyToken({authyId: user.authyId, token: req.body.token}, function (err, tokenRes) {
_440
if (err) {
_440
console.log("Verify Token Error: ", err);
_440
res.status(500).json(err);
_440
return;
_440
}
_440
console.log("Verify Token Response: ", tokenRes);
_440
if (tokenRes.success) {
_440
req.session.authy = true;
_440
}
_440
res.status(200).json(tokenRes);
_440
});
_440
});
_440
};
_440
_440
/**
_440
* Create a OneTouch request.
_440
* The front-end client will poll 12 times at a frequency of 5 seconds before terminating.
_440
* If the status is changed to approved, it quit polling and process the user.
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.createonetouch = function (req, res) {
_440
_440
var username = req.session.username;
_440
console.log("username: ", username);
_440
User.findOne({username: username}).exec(function (err, user) {
_440
if (err) {
_440
console.error("Create OneTouch User Error: ", err);
_440
res.status(500).json(err);
_440
}
_440
_440
var request = {
_440
authyId: user.authyId,
_440
details: {
_440
hidden: {
_440
"test": "This is a"
_440
},
_440
visible: {
_440
"Authy ID": user.authyId,
_440
"Username": user.username,
_440
"Location": 'San Francisco, CA',
_440
"Reason": 'Demo by Authy'
_440
}
_440
},
_440
message: 'Login requested for an Authy Demo account.'
_440
};
_440
_440
authy.createApprovalRequest(request, {ttl: 120}, function (oneTouchErr, oneTouchRes) {
_440
if (oneTouchErr) {
_440
console.error("Create OneTouch Error: ", oneTouchErr);
_440
res.status(500).json(oneTouchErr);
_440
return;
_440
}
_440
console.log("OneTouch Response: ", oneTouchRes);
_440
req.session.uuid = oneTouchRes.approval_request.uuid;
_440
res.status(200).json(oneTouchRes)
_440
});
_440
_440
});
_440
};
_440
_440
/**
_440
* Verify the OneTouch request callback via HMAC inspection.
_440
*
_440
* @url https://en.wikipedia.org/wiki/Hash-based_message_authentication_code
_440
* @url https://gist.github.com/josh-authy/72952c62521480f3dd710dcbad0d8c42
_440
*
_440
* @param req
_440
* @return {Boolean}
_440
*/
_440
function verifyCallback(req) {
_440
_440
var apiKey = config.API_KEY;
_440
_440
var url = req.headers['x-forwarded-proto'] + "://" + req.hostname + req.url;
_440
var method = req.method;
_440
var params = req.body;
_440
_440
// Sort the params.
_440
var sorted_params = qs.stringify(params).split("&").sort().join("&").replace(/%20/g, '+');
_440
_440
var nonce = req.headers["x-authy-signature-nonce"];
_440
var data = nonce + "|" + method + "|" + url + "|" + sorted_params;
_440
_440
var computed_sig = crypto.createHmac('sha256', apiKey).update(data).digest('base64');
_440
var sig = req.headers["x-authy-signature"];
_440
_440
return sig == computed_sig;
_440
}
_440
_440
/**
_440
* Poll for the OneTouch status. Return the response to the client.
_440
* Set the user session 'authy' variable to true if authenticated.
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.checkonetouchstatus = function (req, res) {
_440
_440
var options = {
_440
url: "https://api.authy.com/onetouch/json/approval_requests/" + req.session.uuid,
_440
form: {
_440
"api_key": config.API_KEY
_440
},
_440
headers: {},
_440
qs: {
_440
"api_key": config.API_KEY
_440
},
_440
json: true,
_440
jar: false,
_440
strictSSL: true
_440
};
_440
_440
request.get(options, function (err, response) {
_440
if (err) {
_440
console.log("OneTouch Status Request Error: ", err);
_440
res.status(500).json(err);
_440
}
_440
console.log("OneTouch Status Response: ", response);
_440
if (response.body.approval_request.status === "approved") {
_440
req.session.authy = true;
_440
}
_440
res.status(200).json(response);
_440
});
_440
};
_440
_440
/**
_440
* Register a phone
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.requestPhoneVerification = function (req, res) {
_440
var phone_number = req.body.phone_number;
_440
var country_code = req.body.country_code;
_440
var via = req.body.via;
_440
_440
console.log("body: ", req.body);
_440
_440
if (phone_number && country_code && via) {
_440
phoneReg.requestPhoneVerification(phone_number, country_code, via, function (err, response) {
_440
if (err) {
_440
console.log('error creating phone reg request', err);
_440
res.status(500).json(err);
_440
} else {
_440
console.log('Success register phone API call: ', response);
_440
res.status(200).json(response);
_440
}
_440
});
_440
} else {
_440
console.log('Failed in Register Phone API Call', req.body);
_440
res.status(500).json({error: "Missing fields"});
_440
}
_440
_440
};
_440
_440
/**
_440
* Confirm a phone registration token
_440
*
_440
* @param req
_440
* @param res
_440
*/
_440
exports.verifyPhoneToken = function (req, res) {
_440
var country_code = req.body.country_code;
_440
var phone_number = req.body.phone_number;
_440
var token = req.body.token;
_440
_440
if (phone_number && country_code && token) {
_440
phoneReg.verifyPhoneToken(phone_number, country_code, token, function (err, response) {
_440
if (err) {
_440
console.log('error creating phone reg request', err);
_440
res.status(500).json(err);
_440
} else {
_440
console.log('Confirm phone success confirming code: ', response);
_440
if (response.success) {
_440
req.session.ph_verified = true;
_440
}
_440
res.status(200).json(err);
_440
}
_440
_440
});
_440
} else {
_440
console.log('Failed in Confirm Phone request body: ', req.body);
_440
res.status(500).json({error: "Missing fields"});
_440
}
_440
};
_440
_440
/**
_440
* Create the initial user session.
_440
*
_440
* @param req
_440
* @param res
_440
* @param user
_440
*/
_440
function createSession(req, res, user) {
_440
req.session.regenerate(function () {
_440
req.session.loggedIn = true;
_440
req.session.user = user.id;
_440
req.session.username = user.username;
_440
req.session.msg = 'Authenticated as: ' + user.username;
_440
req.session.authy = false;
_440
req.session.ph_verified = false;
_440
res.status(200).json();
_440
});
_440
}

And there you go, two-factor authentication is on and your Node.js app is protected!


Now that you are keeping the hackers out of this demo app using two-factor authentication, you can find all of the detailed descriptions for options and API calls in our Authy API Reference. If you're also building a registration flow, also check out our Twilio Verify product and the Verification Quickstart which uses this codebase.

For additional guides and tutorials on account security and other products, in Node.js and in our other languages, take a look at the Docs.


Rate this Page: