Skip to contentSkip to navigationSkip to topbar
Rate this Page:

Two-Factor Authentication with Authy, Ruby, and Rails


(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).

This Ruby on Rails(link takes you to an external page) sample application is an example of a typical login flow. To run this sample app yourself, download the code and follow the instructions on GitHub(link takes you to an external page).

Adding two-factor authentication (2FA) to your web application increases the security of your users' data. Multi-factor authentication validates the identity of a user with a two-stage process: first, that they can log into the app, and second that they their mobile device in their possession. This second phase is performed by:

  • Sending them a OneTouch push notification to the Authy app, or
  • Sending them aone-time token via the Authy app, or
  • Sending them a one-time token in a text message sent with Authy via Twilio(link takes you to an external page) .

See how VMware uses Authy 2FA to secure their enterprise mobility management solution.(link takes you to an external page)


Configuring Authy

Configuring Authy page anchor

If you haven't already signed up for Authy(link takes you to an external page), now is the time to to do so(link takes you to an external page). Create your first application, naming it whatever you wish. After you create your application, your "production" API key will be visible on your dashboard(link takes you to an external page).

Once you have an Authy API key, register it as a environment variable.

Register Authy as 2FA provider

Register Authy as 2FA provider page anchor

config/initializers/authy.rb


_10
require 'yaml'
_10
Authy.api_key = Rails.application.secrets.authy_key
_10
Authy.api_uri = 'https://api.authy.com/'

Let's take a look at how you register a user with Authy.


Register a user with Authy

Register a user with Authy page anchor

When a new user signs up for our website, we will call this route. This will save our new user to the database and will register the user with Authy.

In order to set up your application, Authy only needs the user's email, phone number and country code. In order to do a two-factor authentication, we need to make sure we ask for this information at sign-up.

Once we register the user with Authy we get an Authy ID back. This is very important since it's how we will verify the identity of the user with Authy.

Register a User with Authy

Register a User with Authy page anchor

app/controllers/users_controller.rb


_31
class UsersController < ApplicationController
_31
def new
_31
@user = User.new
_31
end
_31
_31
def create
_31
@user = User.new(user_params)
_31
if @user.save
_31
session[:user_id] = @user.id
_31
_31
authy = Authy::API.register_user(
_31
email: @user.email,
_31
cellphone: @user.phone_number,
_31
country_code: @user.country_code
_31
)
_31
@user.update(authy_id: authy.id)
_31
_31
redirect_to account_path
_31
else
_31
render :new
_31
end
_31
end
_31
_31
private
_31
_31
def user_params
_31
params.require(:user).permit(
_31
:email, :password, :name, :country_code, :phone_number
_31
)
_31
end
_31
end

Having registered our user with Authy, we can use Authy's OneTouch feature to log them in.


Log in with Authy OneTouch

Log in with Authy OneTouch page anchor

When a user attempts to log in to our website, we will ask them for a second form of identification. Let's take a look at OneTouch verification first. OneTouch works like this:

  • We attempt to send a user a OneTouch Approval Request .
  • If the user has OneTouch enabled, we will get a success message back.
  • The user hits Approve in their Authy app.
  • Authy makes a POST request to our app with an approved status.
  • We log the user in.

Send the OneTouch request

Send the OneTouch request page anchor

When our user logs in, we immediately attempt to verify their identity with OneTouch. We will fall back gracefully if they don't have a OneTouch device.

Authy allows us to include extra information with our OneTouch request, including a message, a logo, and so on. Add extra information with details['some_detail']. Imagine a scenario where you send a OneTouch request to approve a money transfer. You'd set up details like:


_10
"message" => "Request to Send Money to Jarod's vault",
_10
"details['Request From']" => "Jarod",
_10
"details['Amount Request']" => "1,000,000",
_10
"details['Currency']" => "Galleons",

Implement OneTouch Approval

Implement OneTouch Approval page anchor

app/controllers/sessions_controller.rb


_35
class SessionsController < ApplicationController
_35
def new
_35
@user = User.new
_35
end
_35
_35
def create
_35
@user = User.find_by(email: params[:email])
_35
if @user && @user.authenticate(params[:password])
_35
session[:pre_2fa_auth_user_id] = @user.id
_35
_35
# Try to verify with OneTouch
_35
one_touch = Authy::OneTouch.send_approval_request(
_35
id: @user.authy_id,
_35
message: "Request to Login to Twilio demo app",
_35
details: {
_35
'Email Address' => @user.email,
_35
}
_35
)
_35
status = one_touch['success'] ? :onetouch : :sms
_35
@user.update(authy_status: status)
_35
_35
# Respond to the ajax call that requested this with the approval request body
_35
render json: { success: one_touch['success'] }
_35
else
_35
@user ||= User.new(email: params[:email])
_35
render :new
_35
end
_35
end
_35
_35
def destroy
_35
session[:user_id] = nil
_35
flash[:notice] = "You have been logged out"
_35
redirect_to root_path
_35
end
_35
end

Once we send the request we need to update our user's authy_status based on the response. But first we have to register a OneTouch callback endpoint.


Configure the OneTouch callback

Configure the OneTouch callback page anchor

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.

(information)

Info

In order to verify that a request is coming from Authy, we've written the helper method authenticate_request! that will halt the request if it appears the request isn't coming from Authy.

Here in our callback, we look up the user using the Authy ID sent with the Authy POST request. Ideally at this point we would use a websocket to let our client know that we received a response from Authy. However, we're going to keep it simple and just update the authy_status on the User.

Configure OneTouch Callback

Configure OneTouch Callback page anchor

app/controllers/authy_controller.rb


_76
require 'openssl'
_76
require 'base64'
_76
_76
class AuthyController < ApplicationController
_76
# Before we allow the incoming request to callback, verify
_76
# that it is an Authy request
_76
before_action :authenticate_authy_request, :only => [
_76
:callback
_76
]
_76
_76
protect_from_forgery except: [:callback, :send_token]
_76
_76
# The webhook setup for our Authy application this is where
_76
# the response from a OneTouch request will come
_76
def callback
_76
authy_id = params[:authy_id]
_76
if authy_id != 1234
_76
begin
_76
@user = User.find_by! authy_id: authy_id
_76
@user.update(authy_status: params[:status])
_76
rescue => e
_76
puts e.message
_76
end
_76
end
_76
render plain: 'ok'
_76
end
_76
_76
def one_touch_status
_76
@user = User.find(session[:pre_2fa_auth_user_id])
_76
session[:user_id] = @user.approved? ? @user.id : nil
_76
render plain: @user.authy_status
_76
end
_76
_76
def send_token
_76
@user = User.find(session[:pre_2fa_auth_user_id])
_76
Authy::API.request_sms(id: @user.authy_id)
_76
render plain: 'sending token'
_76
end
_76
_76
def verify
_76
@user = User.find(session[:pre_2fa_auth_user_id])
_76
token = Authy::API.verify(id: @user.authy_id, token: params[:token])
_76
if token.ok?
_76
session[:user_id] = @user.id
_76
session[:pre_2fa_auth_user_id] = nil
_76
redirect_to account_path
_76
else
_76
flash.now[:danger] = "Incorrect code, please try again"
_76
redirect_to new_session_path
_76
end
_76
end
_76
_76
# Authenticate that all requests to our public-facing callback is
_76
# coming from Authy. Adapted from the example at
_76
# https://docs.authy.com/new_doc/authy_onetouch_api#authenticating-callbacks-from-authy-onetouch
_76
private
_76
def authenticate_authy_request
_76
url = request.url
_76
raw_params = JSON.parse(request.raw_post)
_76
nonce = request.headers["X-Authy-Signature-Nonce"]
_76
sorted_params = (Hash[raw_params.sort]).to_query
_76
_76
# data format of Authy digest
_76
data = nonce + "|" + request.method + "|" + url + "|" + sorted_params
_76
_76
digest = OpenSSL::HMAC.digest('sha256', Authy.api_key, data)
_76
digest_in_base64 = Base64.encode64(digest)
_76
_76
theirs = (request.headers['X-Authy-Signature']).strip
_76
mine = digest_in_base64.strip
_76
_76
unless theirs == mine
_76
render plain: 'invalid request signature'
_76
end
_76
end
_76
end

Our application is now capable of using Authy for two-factor authentication. However, we are still missing an important part: the client-side code that will handle it.


Disable unsuccessful callbacks

Disable unsuccessful callbacks page anchor

Scenario: The OneTouch callback URL provided by you is no longer active.

Action: We will disable the OneTouch callback after three consecutive HTTP error responses. We will also:

  • Set the OneTouch callback URL to blank.
  • Send an email notifying you that the OneTouch callback is disabled with details on how to enable the OneTouch callback.

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.


Handle two-factor authentication in the browser

Handle two-factor authentication in the browser page anchor

We've already seen what's happening on the server side, so let's step in front of the cameras and see how our JavaScript is interacting with those server endpoints.

When we expect a OneTouch response, we begin by polling /authy/status until we see an Authy status is not empty. Let's take a look at this controller and see what is happening.

Poll the server until we see the result of the Authy OneTouch login

Poll the server until we see the result of the Authy OneTouch login page anchor

app/assets/javascripts/sessions.js


_43
$(document).ready(function() {
_43
_43
var showTokenForm = function() {
_43
$('.auth-ot').fadeOut(function() {
_43
$('.auth-token').fadeIn('slow');
_43
});
_43
};
_43
_43
var triggerSMSToken = function() {
_43
$.get('/authy/send_token');
_43
};
_43
_43
var checkForOneTouch = function() {
_43
$.get('/authy/status', function(data) {
_43
if (data === 'approved') {
_43
window.location.href = '/account';
_43
} else if (data === 'denied') {
_43
showTokenForm();
_43
triggerSMSToken();
_43
} else {
_43
setTimeout(checkForOneTouch, 2000);
_43
}
_43
});
_43
};
_43
_43
var attemptOneTouchVerification = function(form) {
_43
$.post('/sessions', form, function(data) {
_43
$('#authy-modal').modal({backdrop:'static'},'show');
_43
if (data.success) {
_43
$('.auth-ot').fadeIn();
_43
checkForOneTouch();
_43
} else {
_43
$('.auth-token').fadeIn();
_43
}
_43
});
_43
};
_43
_43
$('#login-form').submit(function(e) {
_43
e.preventDefault();
_43
var formData = $(e.currentTarget).serialize();
_43
attemptOneTouchVerification(formData);
_43
});
_43
});

Let's take a closer look at how we check the login status on the server.


If the value of authy_status is approved, the user will be redirected to the protected content, otherwise we'll show the login form with a message that indicates the request was denied.

Redirect user to the right page based based on authentication status

Redirect user to the right page based based on authentication status page anchor

app/controllers/authy_controller.rb


_76
require 'openssl'
_76
require 'base64'
_76
_76
class AuthyController < ApplicationController
_76
# Before we allow the incoming request to callback, verify
_76
# that it is an Authy request
_76
before_action :authenticate_authy_request, :only => [
_76
:callback
_76
]
_76
_76
protect_from_forgery except: [:callback, :send_token]
_76
_76
# The webhook setup for our Authy application this is where
_76
# the response from a OneTouch request will come
_76
def callback
_76
authy_id = params[:authy_id]
_76
if authy_id != 1234
_76
begin
_76
@user = User.find_by! authy_id: authy_id
_76
@user.update(authy_status: params[:status])
_76
rescue => e
_76
puts e.message
_76
end
_76
end
_76
render plain: 'ok'
_76
end
_76
_76
def one_touch_status
_76
@user = User.find(session[:pre_2fa_auth_user_id])
_76
session[:user_id] = @user.approved? ? @user.id : nil
_76
render plain: @user.authy_status
_76
end
_76
_76
def send_token
_76
@user = User.find(session[:pre_2fa_auth_user_id])
_76
Authy::API.request_sms(id: @user.authy_id)
_76
render plain: 'sending token'
_76
end
_76
_76
def verify
_76
@user = User.find(session[:pre_2fa_auth_user_id])
_76
token = Authy::API.verify(id: @user.authy_id, token: params[:token])
_76
if token.ok?
_76
session[:user_id] = @user.id
_76
session[:pre_2fa_auth_user_id] = nil
_76
redirect_to account_path
_76
else
_76
flash.now[:danger] = "Incorrect code, please try again"
_76
redirect_to new_session_path
_76
end
_76
end
_76
_76
# Authenticate that all requests to our public-facing callback is
_76
# coming from Authy. Adapted from the example at
_76
# https://docs.authy.com/new_doc/authy_onetouch_api#authenticating-callbacks-from-authy-onetouch
_76
private
_76
def authenticate_authy_request
_76
url = request.url
_76
raw_params = JSON.parse(request.raw_post)
_76
nonce = request.headers["X-Authy-Signature-Nonce"]
_76
sorted_params = (Hash[raw_params.sort]).to_query
_76
_76
# data format of Authy digest
_76
data = nonce + "|" + request.method + "|" + url + "|" + sorted_params
_76
_76
digest = OpenSSL::HMAC.digest('sha256', Authy.api_key, data)
_76
digest_in_base64 = Base64.encode64(digest)
_76
_76
theirs = (request.headers['X-Authy-Signature']).strip
_76
mine = digest_in_base64.strip
_76
_76
unless theirs == mine
_76
render plain: 'invalid request signature'
_76
end
_76
end
_76
end

That's it! You've just implemented two-factor authentication using three different methods and the latest in Authy technology.


If you're a Ruby developer working with Twilio, you might enjoy these other tutorials:

Masked Phone Numbers

Protect your users' privacy by anonymously connecting them with Twilio Voice and SMS. Learn how to create disposable phone numbers on-demand, so that two users can communicate without exchanging personal information.

Call Tracking

Use Twilio to track the effectiveness of your marketing campaigns.

Did this help?

Did this help? page anchor

Thanks for checking out this tutorial. If you have any feedback for us, we'd love to hear it. Connect with us on Twitter(link takes you to an external page) and let us know what you build!


Rate this Page: