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.
This Express.js sample application demonstrates how to build a login system that uses two factors of authentication to log in users. Head to the application's README.md to see how to run the application locally.
Adding two-factor authentication (2FA) to your web application increases the security of your user's data. Multi-factor authentication determines the identity of a user by first logging the user into the app, and then validating their mobile device.
For the second factor, we will validate that the user has their mobile phone by either:
See how VMware uses Authy 2FA to secure their enterprise mobility management solution.
If you haven't done so already, now is the time to sign up for Authy. Create your first application, naming it whatever you wish. After you create your application, your production API key will be visible on your dashboard:
Once we have an Authy API key, we store it in this initializer file.
config.js
_11module.exports = {_11 // HTTP port_11 port: process.env.PORT || 3000,_11_11 // Production Authy API key_11 authyApiKey: process.env.AUTHY_API_KEY,_11_11 // MongoDB connection string - MONGO_URL is for local dev,_11 // MONGOLAB_URI is for the MongoLab add-on for Heroku deployment_11 mongoUrl: process.env.MONGOLAB_URI || process.env.MONGO_URL_11};
Now that we've configured our Express app, let's take a look at how we register a user with Authy.
When a new user is created we also register the user with Authy.
All Authy needs to get a user set up for your application is that user's email, phone number and country code. We need to make sure this information is required when the user signs up.
Once we register the User with Authy we get an id
back that we will store as the user's authyId
. This is very important since it's how we will verify the identity of our user with Authy.
models/User.js
_129var mongoose = require('mongoose');_129var bcrypt = require('bcrypt');_129var config = require('../config');_129var onetouch = require('../api/onetouch');_129_129// Create authenticated Authy API client_129var authy = require('authy')(config.authyApiKey);_129_129// Used to generate password hash_129var SALT_WORK_FACTOR = 10;_129_129// Define user model schema_129var UserSchema = new mongoose.Schema({_129 fullName: {_129 type: String,_129 required: true_129 },_129 countryCode: {_129 type: String,_129 required: true_129 },_129 phone: {_129 type: String,_129 required: true_129 },_129 authyId: String,_129 email: {_129 type: String,_129 required: true,_129 unique: true_129 },_129 password: {_129 type: String,_129 required: true_129 },_129 authyStatus: {_129 type: String,_129 default: 'unverified'_129 }_129});_129_129// Middleware executed before save - hash the user's password_129UserSchema.pre('save', function(next) {_129 var self = this;_129_129 // only hash the password if it has been modified (or is new)_129 if (!self.isModified('password')) return next();_129_129 // generate a salt_129 bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {_129 if (err) return next(err);_129_129 // hash the password using our new salt_129 bcrypt.hash(self.password, salt, function(err, hash) {_129 if (err) return next(err);_129_129 // override the cleartext password with the hashed one_129 self.password = hash;_129 next();_129 });_129 });_129_129 if (!self.authyId) {_129 // Register this user if it's a new user_129 authy.register_user(self.email, self.phone, self.countryCode,_129 function(err, response) {_129 if(err){_129 if(response && response.json) {_129 response.json(err);_129 } else {_129 console.error(err);_129 }_129 return;_129 }_129 self.authyId = response.user.id;_129 self.save(function(err, doc) {_129 if (err || !doc) return next(err);_129 self = doc;_129 });_129 });_129 };_129});_129_129// Test candidate password_129UserSchema.methods.comparePassword = function(candidatePassword, cb) {_129 var self = this;_129 bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {_129 if (err) return cb(err);_129 cb(null, isMatch);_129 });_129};_129_129// Send a OneTouch request to this user_129UserSchema.methods.sendOneTouch = function(cb) {_129 var self = this;_129 self.authyStatus = 'unverified';_129 self.save();_129_129 onetouch.send_approval_request(self.authyId, {_129 message: 'Request to Login to Twilio demo app',_129 email: self.email_129 }, function(err, authyres){_129 if (err && err.success != undefined) {_129 authyres = err;_129 err = null;_129 }_129 cb.call(self, err, authyres);_129 });_129};_129_129// Send a 2FA token to this user_129UserSchema.methods.sendAuthyToken = function(cb) {_129 var self = this;_129_129 authy.request_sms(self.authyId, function(err, response) {_129 cb.call(self, err);_129 });_129};_129_129// Test a 2FA token_129UserSchema.methods.verifyAuthyToken = function(otp, cb) {_129 var self = this;_129 authy.verify(self.authyId, otp, function(err, response) {_129 cb.call(self, err, response);_129 });_129};_129_129// Export user model_129module.exports = mongoose.model('User', UserSchema);
When a user attempts to log in to our website, a second form of identification is needed. Let's take a look at Authy's OneTouch verification first.
OneTouch works like so:
success
message back
api/sessions.js
_134var Session = require('../models/Session');_134var User = require('../models/User');_134var error = require('./response_utils').error;_134var ok = require('./response_utils').ok;_134_134// Create a new session, first testing username/password combo_134exports.create = function(request, response) {_134 var email = request.body.email;_134 var candidatePassword = request.body.password;_134_134 // Look for a user by the given username_134 User.findOne({_134 email: email_134 }, function(err, user) {_134 if (err || !user) return invalid();_134_134 // We have a user for that username, test password_134 user.comparePassword(candidatePassword, function(err, match) {_134 if (err || !match) return invalid();_134 return valid(user);_134 });_134 });_134_134 // respond with a 403 for a login error_134 function invalid() {_134 error(response, 403, 'Invalid username/password combination.');_134 }_134_134 // respond with a new session for a valid password, and send a 2FA token_134 function valid(user) {_134 Session.createSessionForUser(user, false, function(err, sess, authyResponse) {_134 if (err || !sess) {_134 error(response, 500,_134 'Error creating session - please log in again.');_134 } else {_134 // Send the unique token for this session and the onetouch response_134 response.send({_134 token: sess.token,_134 authyResponse: authyResponse_134 });_134 }_134 });_134 }_134};_134_134// Destroy the given session (log out)_134exports.destroy = function(request, response) {_134 request.session && request.session.remove(function(err, doc) {_134 if (err) {_134 error(response, 500, 'There was a problem logging you out - please retry.');_134 } else {_134 ok(response);_134 }_134 });_134};_134_134// Public webhook for Authy to POST to_134exports.authyCallback = function(request, response) {_134 var authyId = request.body.authy_id;_134_134 // Respond with a 404 for a no user found error_134 function invalid() {_134 error(response,_134 404,_134 'No user found.'_134 );_134 }_134_134 // Look for a user with the authy_id supplies_134 User.findOne({_134 authyId: authyId_134 }, function(err, user) {_134 if (err || !user) return invalid();_134 user.authyStatus = request.body.status;_134 user.save();_134 });_134 response.end();_134};_134_134// Internal endpoint for checking the status of OneTouch_134exports.authyStatus = function(request, response) {_134 var status = (request.user) ? request.user.authyStatus : 'unverified';_134 if (status == 'approved') {_134 request.session.confirmed = true;_134 request.session.save(function(err) {_134 if (err) return error(response, 500,_134 'There was an error validating your session.');_134 });_134 }_134 if (!request.session) {_134 return error(response, 404, 'No valid session found for this user.');_134 } else {_134 response.send({ status: status });_134 }_134};_134_134// Validate a 2FA token_134exports.verify = function(request, response) {_134 var oneTimeCode = request.body.code;_134_134 if (!request.session || !request.user) {_134 return error(response, 404, 'No valid session found for this token.');_134 }_134_134 // verify entered authy code_134 request.user.verifyAuthyToken(oneTimeCode, function(err) {_134 if (err) return error(response, 401, 'Invalid confirmation code.');_134_134 // otherwise we're good! Validate the session_134 request.session.confirmed = true;_134 request.session.save(function(err) {_134 if (err) return error(response, 500,_134 'There was an error validating your session.');_134_134 response.send({_134 token: request.session.token_134 });_134 });_134 });_134};_134_134// Resend validation code_134exports.resend = function(request, response) {_134 if (!request.user) return error(response, 404,_134 'No user found for this session, please log in again.');_134_134 // Otherwise resend the code_134 request.user.sendAuthyToken(function(err) {_134 if (!request.user) return error(response, 500,_134 'No user found for this session, please log in again.');_134_134 ok(response);_134 });_134};
When our user logs in we immediately attempt to verify their identity with OneTouch. We will fallback gracefully if they don't have a OneTouch device, but we don't know until we try.
Authy lets us pass details with our OneTouch request. These can be messages, logos, and any other details we want to send. We could easily send any number of details by appending details['some_detail']
. You could imagine a scenario where we send a OneTouch request to approve a money transfer:
_10details = {_10 message: "Request to send money to Jarod's vault",_10 from: "Jarod",_10 amount: "1,000,000",_10 currency: "Galleons"_10}
models/User.js
_129var mongoose = require('mongoose');_129var bcrypt = require('bcrypt');_129var config = require('../config');_129var onetouch = require('../api/onetouch');_129_129// Create authenticated Authy API client_129var authy = require('authy')(config.authyApiKey);_129_129// Used to generate password hash_129var SALT_WORK_FACTOR = 10;_129_129// Define user model schema_129var UserSchema = new mongoose.Schema({_129 fullName: {_129 type: String,_129 required: true_129 },_129 countryCode: {_129 type: String,_129 required: true_129 },_129 phone: {_129 type: String,_129 required: true_129 },_129 authyId: String,_129 email: {_129 type: String,_129 required: true,_129 unique: true_129 },_129 password: {_129 type: String,_129 required: true_129 },_129 authyStatus: {_129 type: String,_129 default: 'unverified'_129 }_129});_129_129// Middleware executed before save - hash the user's password_129UserSchema.pre('save', function(next) {_129 var self = this;_129_129 // only hash the password if it has been modified (or is new)_129 if (!self.isModified('password')) return next();_129_129 // generate a salt_129 bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {_129 if (err) return next(err);_129_129 // hash the password using our new salt_129 bcrypt.hash(self.password, salt, function(err, hash) {_129 if (err) return next(err);_129_129 // override the cleartext password with the hashed one_129 self.password = hash;_129 next();_129 });_129 });_129_129 if (!self.authyId) {_129 // Register this user if it's a new user_129 authy.register_user(self.email, self.phone, self.countryCode,_129 function(err, response) {_129 if(err){_129 if(response && response.json) {_129 response.json(err);_129 } else {_129 console.error(err);_129 }_129 return;_129 }_129 self.authyId = response.user.id;_129 self.save(function(err, doc) {_129 if (err || !doc) return next(err);_129 self = doc;_129 });_129 });_129 };_129});_129_129// Test candidate password_129UserSchema.methods.comparePassword = function(candidatePassword, cb) {_129 var self = this;_129 bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {_129 if (err) return cb(err);_129 cb(null, isMatch);_129 });_129};_129_129// Send a OneTouch request to this user_129UserSchema.methods.sendOneTouch = function(cb) {_129 var self = this;_129 self.authyStatus = 'unverified';_129 self.save();_129_129 onetouch.send_approval_request(self.authyId, {_129 message: 'Request to Login to Twilio demo app',_129 email: self.email_129 }, function(err, authyres){_129 if (err && err.success != undefined) {_129 authyres = err;_129 err = null;_129 }_129 cb.call(self, err, authyres);_129 });_129};_129_129// Send a 2FA token to this user_129UserSchema.methods.sendAuthyToken = function(cb) {_129 var self = this;_129_129 authy.request_sms(self.authyId, function(err, response) {_129 cb.call(self, err);_129 });_129};_129_129// Test a 2FA token_129UserSchema.methods.verifyAuthyToken = function(otp, cb) {_129 var self = this;_129 authy.verify(self.authyId, otp, function(err, response) {_129 cb.call(self, err, response);_129 });_129};_129_129// Export user model_129module.exports = mongoose.model('User', UserSchema);
Note: We need some way to check the status of the user's two-factor process. In this case, we do so by updating the User.authyStatus
attribute. It's important we reset this before we log the user in.
In order for our app to know what the user did after we sent the OneTouch request, we need to register a callback endpoint with Authy.
api/sessions.js
_134var Session = require('../models/Session');_134var User = require('../models/User');_134var error = require('./response_utils').error;_134var ok = require('./response_utils').ok;_134_134// Create a new session, first testing username/password combo_134exports.create = function(request, response) {_134 var email = request.body.email;_134 var candidatePassword = request.body.password;_134_134 // Look for a user by the given username_134 User.findOne({_134 email: email_134 }, function(err, user) {_134 if (err || !user) return invalid();_134_134 // We have a user for that username, test password_134 user.comparePassword(candidatePassword, function(err, match) {_134 if (err || !match) return invalid();_134 return valid(user);_134 });_134 });_134_134 // respond with a 403 for a login error_134 function invalid() {_134 error(response, 403, 'Invalid username/password combination.');_134 }_134_134 // respond with a new session for a valid password, and send a 2FA token_134 function valid(user) {_134 Session.createSessionForUser(user, false, function(err, sess, authyResponse) {_134 if (err || !sess) {_134 error(response, 500,_134 'Error creating session - please log in again.');_134 } else {_134 // Send the unique token for this session and the onetouch response_134 response.send({_134 token: sess.token,_134 authyResponse: authyResponse_134 });_134 }_134 });_134 }_134};_134_134// Destroy the given session (log out)_134exports.destroy = function(request, response) {_134 request.session && request.session.remove(function(err, doc) {_134 if (err) {_134 error(response, 500, 'There was a problem logging you out - please retry.');_134 } else {_134 ok(response);_134 }_134 });_134};_134_134// Public webhook for Authy to POST to_134exports.authyCallback = function(request, response) {_134 var authyId = request.body.authy_id;_134_134 // Respond with a 404 for a no user found error_134 function invalid() {_134 error(response,_134 404,_134 'No user found.'_134 );_134 }_134_134 // Look for a user with the authy_id supplies_134 User.findOne({_134 authyId: authyId_134 }, function(err, user) {_134 if (err || !user) return invalid();_134 user.authyStatus = request.body.status;_134 user.save();_134 });_134 response.end();_134};_134_134// Internal endpoint for checking the status of OneTouch_134exports.authyStatus = function(request, response) {_134 var status = (request.user) ? request.user.authyStatus : 'unverified';_134 if (status == 'approved') {_134 request.session.confirmed = true;_134 request.session.save(function(err) {_134 if (err) return error(response, 500,_134 'There was an error validating your session.');_134 });_134 }_134 if (!request.session) {_134 return error(response, 404, 'No valid session found for this user.');_134 } else {_134 response.send({ status: status });_134 }_134};_134_134// Validate a 2FA token_134exports.verify = function(request, response) {_134 var oneTimeCode = request.body.code;_134_134 if (!request.session || !request.user) {_134 return error(response, 404, 'No valid session found for this token.');_134 }_134_134 // verify entered authy code_134 request.user.verifyAuthyToken(oneTimeCode, function(err) {_134 if (err) return error(response, 401, 'Invalid confirmation code.');_134_134 // otherwise we're good! Validate the session_134 request.session.confirmed = true;_134 request.session.save(function(err) {_134 if (err) return error(response, 500,_134 'There was an error validating your session.');_134_134 response.send({_134 token: request.session.token_134 });_134 });_134 });_134};_134_134// Resend validation code_134exports.resend = function(request, response) {_134 if (!request.user) return error(response, 404,_134 'No user found for this session, please log in again.');_134_134 // Otherwise resend the code_134 request.user.sendAuthyToken(function(err) {_134 if (!request.user) return error(response, 500,_134 'No user found for this session, please log in again.');_134_134 ok(response);_134 });_134};
Here in our callback, we look up the user using the authy_id
sent with the Authy POST request. At this point we would ideally use a websocket to let our client know that we received a response from Authy. However, for this version we're going to keep it simple and just update the authyStatus
on the user. Now all our client-side code needs to do is check for user.authyStatus.approved
before logging in the user.
Scenario: The OneTouch callback URL provided by you is no longer active.
Action: We will disable the OneTouch callback after 3 consecutive HTTP error responses. We will also
How to enable OneTouch callback? You need to update the OneTouch callback endpoint, which will allow the OneTouch callback.
Visit the Twilio Console: Console > Authy > Applications > {ApplicationName} > Push Authentication > Webhooks > Endpoint/URL to update the Endpoint/URL with a valid OneTouch callback URL.
Our user interface for this example is a single page application written using Backbone and jQuery.
We've already taken a look at what's happening on the server side, so let's step in front of the cameras now and see how our JavaScript is interacting with those server endpoints.
First we hijack the login form submitted and pass the data to our /session
controller using Ajax. Depending on how that endpoint responds we will either ask the user for a token or await their OneTouch response.
If we expect a OneTouch response, we will begin polling /authy/status
until we see that the OneTouch login was either approved or denied. Take a look at this controller and see what is happening.
public/app/views/Login.js
_81(function() {_81 app.views.LoginView = app.views.BaseView.extend({_81 // name of the template file to load from the server_81 templateName: 'login',_81_81 // UI events_81 events: {_81 'submit #loginForm': 'login'_81 },_81_81 initialize: function() {_81 var self = this;_81 // default behavior, render page into #page section_81 app.router.on('route:login', function() {_81 self.render();_81 });_81 },_81_81 // Hit login service_81 login: function(e) {_81 var self = this;_81_81 e.preventDefault();_81 app.set('message', null);_81 $.ajax('/session', {_81 method: 'POST',_81 data: {_81 email: self.$('#email').val(),_81 password: self.$('#password').val()_81 }_81 }).done(function(data) {_81 // If session returns oneTouch status.success wait for oneStatus approval_81 app.set('token', data.token);_81 if (data.authyResponse.success) {_81 app.set('onetouch', true);_81 app.set('message', {_81 error: false,_81 message: 'Awaiting One Touch approval.'_81 });_81 self.checkOneTouchStatus();_81 } else {_81 app.router.navigate('verify', {_81 trigger: true_81 });_81 }_81 }).fail(function(err) {_81 app.set('message', {_81 error: true,_81 message: err.responseJSON.message ||_81 'Sorry, an error occurred, please log in again.'_81 });_81 });_81 },_81_81 checkOneTouchStatus: function() {_81 var self = this;_81 $.ajax('/authy/status', {_81 method: 'GET',_81 headers: {_81 'X-API-TOKEN': app.get('token')_81 }_81 }).done(function(data) {_81 if (data.status == 'approved') {_81 app.router.navigate('user', {_81 trigger: true_81 });_81 } else if (data.status == 'denied') {_81 app.router.navigate('verify', {_81 trigger: true_81 });_81 app.set('message', {_81 error: true,_81 message: 'OneTouch Login request denied.'_81 });_81 } else {_81 setTimeout(self.checkOneTouchStatus(), 3000);_81 }_81 });_81 }_81 });_81})();
Here is the endpoint that our javascript is polling. It is waiting for the user status to be either 'Approved' or 'Denied'. If the user has approved the OneTouch request, we will save their session as confirmed
, which officially logs them in.
If the request was denied we render the /verify
page and ask the user to log in with a Token.
api/sessions.js
_134var Session = require('../models/Session');_134var User = require('../models/User');_134var error = require('./response_utils').error;_134var ok = require('./response_utils').ok;_134_134// Create a new session, first testing username/password combo_134exports.create = function(request, response) {_134 var email = request.body.email;_134 var candidatePassword = request.body.password;_134_134 // Look for a user by the given username_134 User.findOne({_134 email: email_134 }, function(err, user) {_134 if (err || !user) return invalid();_134_134 // We have a user for that username, test password_134 user.comparePassword(candidatePassword, function(err, match) {_134 if (err || !match) return invalid();_134 return valid(user);_134 });_134 });_134_134 // respond with a 403 for a login error_134 function invalid() {_134 error(response, 403, 'Invalid username/password combination.');_134 }_134_134 // respond with a new session for a valid password, and send a 2FA token_134 function valid(user) {_134 Session.createSessionForUser(user, false, function(err, sess, authyResponse) {_134 if (err || !sess) {_134 error(response, 500,_134 'Error creating session - please log in again.');_134 } else {_134 // Send the unique token for this session and the onetouch response_134 response.send({_134 token: sess.token,_134 authyResponse: authyResponse_134 });_134 }_134 });_134 }_134};_134_134// Destroy the given session (log out)_134exports.destroy = function(request, response) {_134 request.session && request.session.remove(function(err, doc) {_134 if (err) {_134 error(response, 500, 'There was a problem logging you out - please retry.');_134 } else {_134 ok(response);_134 }_134 });_134};_134_134// Public webhook for Authy to POST to_134exports.authyCallback = function(request, response) {_134 var authyId = request.body.authy_id;_134_134 // Respond with a 404 for a no user found error_134 function invalid() {_134 error(response,_134 404,_134 'No user found.'_134 );_134 }_134_134 // Look for a user with the authy_id supplies_134 User.findOne({_134 authyId: authyId_134 }, function(err, user) {_134 if (err || !user) return invalid();_134 user.authyStatus = request.body.status;_134 user.save();_134 });_134 response.end();_134};_134_134// Internal endpoint for checking the status of OneTouch_134exports.authyStatus = function(request, response) {_134 var status = (request.user) ? request.user.authyStatus : 'unverified';_134 if (status == 'approved') {_134 request.session.confirmed = true;_134 request.session.save(function(err) {_134 if (err) return error(response, 500,_134 'There was an error validating your session.');_134 });_134 }_134 if (!request.session) {_134 return error(response, 404, 'No valid session found for this user.');_134 } else {_134 response.send({ status: status });_134 }_134};_134_134// Validate a 2FA token_134exports.verify = function(request, response) {_134 var oneTimeCode = request.body.code;_134_134 if (!request.session || !request.user) {_134 return error(response, 404, 'No valid session found for this token.');_134 }_134_134 // verify entered authy code_134 request.user.verifyAuthyToken(oneTimeCode, function(err) {_134 if (err) return error(response, 401, 'Invalid confirmation code.');_134_134 // otherwise we're good! Validate the session_134 request.session.confirmed = true;_134 request.session.save(function(err) {_134 if (err) return error(response, 500,_134 'There was an error validating your session.');_134_134 response.send({_134 token: request.session.token_134 });_134 });_134 });_134};_134_134// Resend validation code_134exports.resend = function(request, response) {_134 if (!request.user) return error(response, 404,_134 'No user found for this session, please log in again.');_134_134 // Otherwise resend the code_134 request.user.sendAuthyToken(function(err) {_134 if (!request.user) return error(response, 500,_134 'No user found for this session, please log in again.');_134_134 ok(response);_134 });_134};
Now let's take a look at how we handle two-factor with tokens.
Once there is an Authy user ID associated with our user model, we can request that an SMS verification token be sent out to the user's phone. Authy supports token validation in their mobile app as well, so if our user has the app it will default to sending a push notification instead of an SMS.
If needed, we can call this method on the user instance multiple times. This is what happens every time the user clicks "Resend Code" on the web form.
models/User.js
_129var mongoose = require('mongoose');_129var bcrypt = require('bcrypt');_129var config = require('../config');_129var onetouch = require('../api/onetouch');_129_129// Create authenticated Authy API client_129var authy = require('authy')(config.authyApiKey);_129_129// Used to generate password hash_129var SALT_WORK_FACTOR = 10;_129_129// Define user model schema_129var UserSchema = new mongoose.Schema({_129 fullName: {_129 type: String,_129 required: true_129 },_129 countryCode: {_129 type: String,_129 required: true_129 },_129 phone: {_129 type: String,_129 required: true_129 },_129 authyId: String,_129 email: {_129 type: String,_129 required: true,_129 unique: true_129 },_129 password: {_129 type: String,_129 required: true_129 },_129 authyStatus: {_129 type: String,_129 default: 'unverified'_129 }_129});_129_129// Middleware executed before save - hash the user's password_129UserSchema.pre('save', function(next) {_129 var self = this;_129_129 // only hash the password if it has been modified (or is new)_129 if (!self.isModified('password')) return next();_129_129 // generate a salt_129 bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {_129 if (err) return next(err);_129_129 // hash the password using our new salt_129 bcrypt.hash(self.password, salt, function(err, hash) {_129 if (err) return next(err);_129_129 // override the cleartext password with the hashed one_129 self.password = hash;_129 next();_129 });_129 });_129_129 if (!self.authyId) {_129 // Register this user if it's a new user_129 authy.register_user(self.email, self.phone, self.countryCode,_129 function(err, response) {_129 if(err){_129 if(response && response.json) {_129 response.json(err);_129 } else {_129 console.error(err);_129 }_129 return;_129 }_129 self.authyId = response.user.id;_129 self.save(function(err, doc) {_129 if (err || !doc) return next(err);_129 self = doc;_129 });_129 });_129 };_129});_129_129// Test candidate password_129UserSchema.methods.comparePassword = function(candidatePassword, cb) {_129 var self = this;_129 bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {_129 if (err) return cb(err);_129 cb(null, isMatch);_129 });_129};_129_129// Send a OneTouch request to this user_129UserSchema.methods.sendOneTouch = function(cb) {_129 var self = this;_129 self.authyStatus = 'unverified';_129 self.save();_129_129 onetouch.send_approval_request(self.authyId, {_129 message: 'Request to Login to Twilio demo app',_129 email: self.email_129 }, function(err, authyres){_129 if (err && err.success != undefined) {_129 authyres = err;_129 err = null;_129 }_129 cb.call(self, err, authyres);_129 });_129};_129_129// Send a 2FA token to this user_129UserSchema.methods.sendAuthyToken = function(cb) {_129 var self = this;_129_129 authy.request_sms(self.authyId, function(err, response) {_129 cb.call(self, err);_129 });_129};_129_129// Test a 2FA token_129UserSchema.methods.verifyAuthyToken = function(otp, cb) {_129 var self = this;_129 authy.verify(self.authyId, otp, function(err, response) {_129 cb.call(self, err, response);_129 });_129};_129_129// Export user model_129module.exports = mongoose.model('User', UserSchema);
Our Express route handler will grab the code submitted on the form in order to validate it. The connect middleware function executes before this handler and adds a user
property to the request
object that contains a Mongoose model instance representing the user associated with this session. We use verifyAuthyToken
on the User
model to check if the code submitted by the user is legit.
api/sessions.js
_134var Session = require('../models/Session');_134var User = require('../models/User');_134var error = require('./response_utils').error;_134var ok = require('./response_utils').ok;_134_134// Create a new session, first testing username/password combo_134exports.create = function(request, response) {_134 var email = request.body.email;_134 var candidatePassword = request.body.password;_134_134 // Look for a user by the given username_134 User.findOne({_134 email: email_134 }, function(err, user) {_134 if (err || !user) return invalid();_134_134 // We have a user for that username, test password_134 user.comparePassword(candidatePassword, function(err, match) {_134 if (err || !match) return invalid();_134 return valid(user);_134 });_134 });_134_134 // respond with a 403 for a login error_134 function invalid() {_134 error(response, 403, 'Invalid username/password combination.');_134 }_134_134 // respond with a new session for a valid password, and send a 2FA token_134 function valid(user) {_134 Session.createSessionForUser(user, false, function(err, sess, authyResponse) {_134 if (err || !sess) {_134 error(response, 500,_134 'Error creating session - please log in again.');_134 } else {_134 // Send the unique token for this session and the onetouch response_134 response.send({_134 token: sess.token,_134 authyResponse: authyResponse_134 });_134 }_134 });_134 }_134};_134_134// Destroy the given session (log out)_134exports.destroy = function(request, response) {_134 request.session && request.session.remove(function(err, doc) {_134 if (err) {_134 error(response, 500, 'There was a problem logging you out - please retry.');_134 } else {_134 ok(response);_134 }_134 });_134};_134_134// Public webhook for Authy to POST to_134exports.authyCallback = function(request, response) {_134 var authyId = request.body.authy_id;_134_134 // Respond with a 404 for a no user found error_134 function invalid() {_134 error(response,_134 404,_134 'No user found.'_134 );_134 }_134_134 // Look for a user with the authy_id supplies_134 User.findOne({_134 authyId: authyId_134 }, function(err, user) {_134 if (err || !user) return invalid();_134 user.authyStatus = request.body.status;_134 user.save();_134 });_134 response.end();_134};_134_134// Internal endpoint for checking the status of OneTouch_134exports.authyStatus = function(request, response) {_134 var status = (request.user) ? request.user.authyStatus : 'unverified';_134 if (status == 'approved') {_134 request.session.confirmed = true;_134 request.session.save(function(err) {_134 if (err) return error(response, 500,_134 'There was an error validating your session.');_134 });_134 }_134 if (!request.session) {_134 return error(response, 404, 'No valid session found for this user.');_134 } else {_134 response.send({ status: status });_134 }_134};_134_134// Validate a 2FA token_134exports.verify = function(request, response) {_134 var oneTimeCode = request.body.code;_134_134 if (!request.session || !request.user) {_134 return error(response, 404, 'No valid session found for this token.');_134 }_134_134 // verify entered authy code_134 request.user.verifyAuthyToken(oneTimeCode, function(err) {_134 if (err) return error(response, 401, 'Invalid confirmation code.');_134_134 // otherwise we're good! Validate the session_134 request.session.confirmed = true;_134 request.session.save(function(err) {_134 if (err) return error(response, 500,_134 'There was an error validating your session.');_134_134 response.send({_134 token: request.session.token_134 });_134 });_134 });_134};_134_134// Resend validation code_134exports.resend = function(request, response) {_134 if (!request.user) return error(response, 404,_134 'No user found for this session, please log in again.');_134_134 // Otherwise resend the code_134 request.user.sendAuthyToken(function(err) {_134 if (!request.user) return error(response, 500,_134 'No user found for this session, please log in again.');_134_134 ok(response);_134 });_134};
That's it! We've just implemented two-factor authentication using three different methods and the latest in Authy technology.
If you're a Node.js developer working with Twilio, you might want to check out these other tutorials.
Increase the security of your login system by verifying a user's mobile phone.
Faster than email and less likely to get blocked, text messages are great for timed alerts and notifications. Learn how to send out SMS (and MMS) notifications to a list of server administrators.
Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Connect with us on Twitter and let us know what you build!