Two-Factor Authentication with Authy, Ruby and Rails

Download the Code

This Ruby on Rails 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.

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 validating once by logging into the app, and second by validating their mobile device.

For the second factor, we will validate that the user has their mobile phone by either:

  • Sending them a OneTouch push notification to their mobile Authy app or
  • Sending them a token through their mobile Authy app or
  • Sending them a one-time token in a text message sent with Authy via Twilio.

Here's how this works at a high level:

2FA High Level

See how VMware uses Authy 2FA to secure their enterprise mobility management solution.

Configuring Authy

If you haven't 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:

Authy Dashboard

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

Loading Code Samples...
Language
require 'yaml'
Authy.api_key = Rails.application.secrets.authy_key
Authy.api_uri = 'https://api.authy.com/'
config/initializers/authy.rb
Register Authy as 2FA provider

config/initializers/authy.rb

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

Register a User with Authy

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 our User with Authy.

Loading Code Samples...
Language
class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id

      authy = Authy::API.register_user(
        email: @user.email,
        cellphone: @user.phone_number,
        country_code: @user.country_code
      )
      @user.update(authy_id: authy.id)
      
      redirect_to account_path
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(
      :email, :password, :name, :country_code, :phone_number
    )
  end
end
app/controllers/users_controller.rb
Register a User with Authy

app/controllers/users_controller.rb

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

Log in with Authy OneTouch

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.

Authy OneTouch Approval

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

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 allows us to input details with our OneTouch request, including a message, a logo and so on. We could easily send any amount of details by appending details['some_detail']. You could imagine a scenario where we send a OneTouch request to approve a money transfer.

"message" => "Request to Send Money to Jarod's vault",
"details['Request From']" => "Jarod",
"details['Amount Request']" => "1,000,000",
"details['Currency']" => "Galleons",
Loading Code Samples...
Language
class SessionsController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.find_by(email: params[:email])
    if @user && @user.authenticate(params[:password])
      session[:pre_2fa_auth_user_id] = @user.id

      # Try to verify with OneTouch
      one_touch = Authy::OneTouch.send_approval_request(
        id: @user.authy_id,
        message: "Request to Login to Twilio demo app",
        details: {
          'Email Address' => @user.email,
        }
      )
      status = one_touch['success'] ? :onetouch : :sms
      @user.update(authy_status: status)

      # Respond to the ajax call that requested this with the approval request body
      render json: { success: one_touch['success'] }
    else
      @user ||= User.new(email: params[:email])
      render :new
    end
  end

  def destroy
    session[:user_id] = nil
    flash[:notice] = "You have been logged out"
    redirect_to root_path
  end
end
app/controllers/sessions_controller.rb
Implement OneTouch Approval

app/controllers/sessions_controller.rb

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

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.

Authy OneTouch Callback

Note: In order to verify that the request is coming from Authy, we've written the helper method authenticate_request! that will halt the request if it appears it 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 probably 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 authy_status on the User.

Loading Code Samples...
Language
require 'openssl'
require 'base64'

class AuthyController < ApplicationController
  # Before we allow the incoming request to callback, verify
  # that it is an Authy request
  before_filter :authenticate_authy_request, :only => [
    :callback
  ]

  protect_from_forgery except: [:callback, :send_token]

  # The webhook setup for our Authy application this is where
  # the response from a OneTouch request will come
  def callback
    authy_id = params[:authy_id]
    begin
      @user = User.find_by! authy_id: authy_id
      @user.update(authy_status: params[:status])
    rescue => e
      puts e.message
    end
    render plain: 'OK'
  end

  def one_touch_status
    @user = User.find(session[:pre_2fa_auth_user_id])
    session[:user_id] = @user.approved? ? @user.id : nil
    render plain: @user.authy_status
  end

  def send_token
    @user = User.find(session[:pre_2fa_auth_user_id])
    Authy::API.request_sms(id: @user.authy_id)
    render plain: 'sending token'
  end

  def verify
    @user = User.find(session[:pre_2fa_auth_user_id])
    token = Authy::API.verify(id: @user.authy_id, token: params[:token])
    if token.ok?
      session[:user_id] = @user.id
      session[:pre_2fa_auth_user_id] = nil
      redirect_to account_path
    else
      flash.now[:danger] = "Incorrect code, please try again"
      redirect_to new_session_path
    end
  end

  # Authenticate that all requests to our public-facing callback is
  # coming from Authy. Adapted from the example at 
  # https://docs.authy.com/new_doc/authy_onetouch_api#authenticating-callbacks-from-authy-onetouch
  private
  def authenticate_authy_request
    url = request.url
    raw_params = JSON.parse(request.raw_post)
    nonce = request.headers["X-Authy-Signature-Nonce"]
    sorted_params = (Hash[raw_params.sort]).to_query

    # data format of Authy digest
    data = nonce + "|" + request.method + "|" + url + "|" + sorted_params

    digest = OpenSSL::HMAC.digest('sha256', Authy.api_key, data)
    digest_in_base64 = Base64.encode64(digest)

    theirs = (request.headers['X-Authy-Signature']).strip
    mine = digest_in_base64.strip

    unless theirs == mine
      render plain: 'invalid request signature'
    end
  end
end
app/controllers/authy_controller.rb
Configure OneTouch Callback

app/controllers/authy_controller.rb

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.

Handle Two-Factor in the Browser

We've already taken a look at 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 will 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.

Loading Code Samples...
Language
$(document).ready(function() {

  $('#login-form').submit(function(e) {
    e.preventDefault();
    formData = $(e.currentTarget).serialize();
    attemptOneTouchVerification(formData);
  })

  var attemptOneTouchVerification = function(form) {
    $.post( "/sessions", form, function(data) {
      $('#authy-modal').modal({backdrop:'static'},'show')
      if (data.success) {
        $('.auth-ot').fadeIn()
        checkForOneTouch();
      } else {
        $('.auth-token').fadeIn()
      }
    })
  };

  var checkForOneTouch = function() {
    $.get( "/authy/status", function(data) {
      
      if (data == 'approved') {
        window.location.href = "/account";
      } else if (data == 'denied') {
        showTokenForm();
        triggerSMSToken();
      } else {
        setTimeout(checkForOneTouch, 2000);
      }
    })
  };

  var showTokenForm = function() {
    $('.auth-ot').fadeOut(function() {
      $('.auth-token').fadeIn('slow')
    })
  };

  var triggerSMSToken = function() {
    $.get("/authy/send_token")
  };
})
app/assets/javascripts/sessions.js
Poll the server until we see the result of the Authy OneTouch login

app/assets/javascripts/sessions.js

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

Finish the 2FA Step

If 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.

Loading Code Samples...
Language
require 'openssl'
require 'base64'

class AuthyController < ApplicationController
  # Before we allow the incoming request to callback, verify
  # that it is an Authy request
  before_filter :authenticate_authy_request, :only => [
    :callback
  ]

  protect_from_forgery except: [:callback, :send_token]

  # The webhook setup for our Authy application this is where
  # the response from a OneTouch request will come
  def callback
    authy_id = params[:authy_id]
    begin
      @user = User.find_by! authy_id: authy_id
      @user.update(authy_status: params[:status])
    rescue => e
      puts e.message
    end
    render plain: 'OK'
  end

  def one_touch_status
    @user = User.find(session[:pre_2fa_auth_user_id])
    session[:user_id] = @user.approved? ? @user.id : nil
    render plain: @user.authy_status
  end

  def send_token
    @user = User.find(session[:pre_2fa_auth_user_id])
    Authy::API.request_sms(id: @user.authy_id)
    render plain: 'sending token'
  end

  def verify
    @user = User.find(session[:pre_2fa_auth_user_id])
    token = Authy::API.verify(id: @user.authy_id, token: params[:token])
    if token.ok?
      session[:user_id] = @user.id
      session[:pre_2fa_auth_user_id] = nil
      redirect_to account_path
    else
      flash.now[:danger] = "Incorrect code, please try again"
      redirect_to new_session_path
    end
  end

  # Authenticate that all requests to our public-facing callback is
  # coming from Authy. Adapted from the example at 
  # https://docs.authy.com/new_doc/authy_onetouch_api#authenticating-callbacks-from-authy-onetouch
  private
  def authenticate_authy_request
    url = request.url
    raw_params = JSON.parse(request.raw_post)
    nonce = request.headers["X-Authy-Signature-Nonce"]
    sorted_params = (Hash[raw_params.sort]).to_query

    # data format of Authy digest
    data = nonce + "|" + request.method + "|" + url + "|" + sorted_params

    digest = OpenSSL::HMAC.digest('sha256', Authy.api_key, data)
    digest_in_base64 = Base64.encode64(digest)

    theirs = (request.headers['X-Authy-Signature']).strip
    mine = digest_in_base64.strip

    unless theirs == mine
      render plain: 'invalid request signature'
    end
  end
end
app/controllers/authy_controller.rb
Redirect user to the right page based based on authentication status

app/controllers/authy_controller.rb

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

Where to next?

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 two users can communicate without exchanging personal information.

Call Tracking

Use Twilio to track the effectiveness of your marketing campaigns.

Did this help?

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!

Jarod Reyes
Jose Oliveros
David Prothero
Andrew Baker
Agustin Camino

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
require 'yaml'
Authy.api_key = Rails.application.secrets.authy_key
Authy.api_uri = 'https://api.authy.com/'
class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id

      authy = Authy::API.register_user(
        email: @user.email,
        cellphone: @user.phone_number,
        country_code: @user.country_code
      )
      @user.update(authy_id: authy.id)
      
      redirect_to account_path
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(
      :email, :password, :name, :country_code, :phone_number
    )
  end
end
class SessionsController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.find_by(email: params[:email])
    if @user && @user.authenticate(params[:password])
      session[:pre_2fa_auth_user_id] = @user.id

      # Try to verify with OneTouch
      one_touch = Authy::OneTouch.send_approval_request(
        id: @user.authy_id,
        message: "Request to Login to Twilio demo app",
        details: {
          'Email Address' => @user.email,
        }
      )
      status = one_touch['success'] ? :onetouch : :sms
      @user.update(authy_status: status)

      # Respond to the ajax call that requested this with the approval request body
      render json: { success: one_touch['success'] }
    else
      @user ||= User.new(email: params[:email])
      render :new
    end
  end

  def destroy
    session[:user_id] = nil
    flash[:notice] = "You have been logged out"
    redirect_to root_path
  end
end
require 'openssl'
require 'base64'

class AuthyController < ApplicationController
  # Before we allow the incoming request to callback, verify
  # that it is an Authy request
  before_filter :authenticate_authy_request, :only => [
    :callback
  ]

  protect_from_forgery except: [:callback, :send_token]

  # The webhook setup for our Authy application this is where
  # the response from a OneTouch request will come
  def callback
    authy_id = params[:authy_id]
    begin
      @user = User.find_by! authy_id: authy_id
      @user.update(authy_status: params[:status])
    rescue => e
      puts e.message
    end
    render plain: 'OK'
  end

  def one_touch_status
    @user = User.find(session[:pre_2fa_auth_user_id])
    session[:user_id] = @user.approved? ? @user.id : nil
    render plain: @user.authy_status
  end

  def send_token
    @user = User.find(session[:pre_2fa_auth_user_id])
    Authy::API.request_sms(id: @user.authy_id)
    render plain: 'sending token'
  end

  def verify
    @user = User.find(session[:pre_2fa_auth_user_id])
    token = Authy::API.verify(id: @user.authy_id, token: params[:token])
    if token.ok?
      session[:user_id] = @user.id
      session[:pre_2fa_auth_user_id] = nil
      redirect_to account_path
    else
      flash.now[:danger] = "Incorrect code, please try again"
      redirect_to new_session_path
    end
  end

  # Authenticate that all requests to our public-facing callback is
  # coming from Authy. Adapted from the example at 
  # https://docs.authy.com/new_doc/authy_onetouch_api#authenticating-callbacks-from-authy-onetouch
  private
  def authenticate_authy_request
    url = request.url
    raw_params = JSON.parse(request.raw_post)
    nonce = request.headers["X-Authy-Signature-Nonce"]
    sorted_params = (Hash[raw_params.sort]).to_query

    # data format of Authy digest
    data = nonce + "|" + request.method + "|" + url + "|" + sorted_params

    digest = OpenSSL::HMAC.digest('sha256', Authy.api_key, data)
    digest_in_base64 = Base64.encode64(digest)

    theirs = (request.headers['X-Authy-Signature']).strip
    mine = digest_in_base64.strip

    unless theirs == mine
      render plain: 'invalid request signature'
    end
  end
end
$(document).ready(function() {

  $('#login-form').submit(function(e) {
    e.preventDefault();
    formData = $(e.currentTarget).serialize();
    attemptOneTouchVerification(formData);
  })

  var attemptOneTouchVerification = function(form) {
    $.post( "/sessions", form, function(data) {
      $('#authy-modal').modal({backdrop:'static'},'show')
      if (data.success) {
        $('.auth-ot').fadeIn()
        checkForOneTouch();
      } else {
        $('.auth-token').fadeIn()
      }
    })
  };

  var checkForOneTouch = function() {
    $.get( "/authy/status", function(data) {
      
      if (data == 'approved') {
        window.location.href = "/account";
      } else if (data == 'denied') {
        showTokenForm();
        triggerSMSToken();
      } else {
        setTimeout(checkForOneTouch, 2000);
      }
    })
  };

  var showTokenForm = function() {
    $('.auth-ot').fadeOut(function() {
      $('.auth-token').fadeIn('slow')
    })
  };

  var triggerSMSToken = function() {
    $.get("/authy/send_token")
  };
})
require 'openssl'
require 'base64'

class AuthyController < ApplicationController
  # Before we allow the incoming request to callback, verify
  # that it is an Authy request
  before_filter :authenticate_authy_request, :only => [
    :callback
  ]

  protect_from_forgery except: [:callback, :send_token]

  # The webhook setup for our Authy application this is where
  # the response from a OneTouch request will come
  def callback
    authy_id = params[:authy_id]
    begin
      @user = User.find_by! authy_id: authy_id
      @user.update(authy_status: params[:status])
    rescue => e
      puts e.message
    end
    render plain: 'OK'
  end

  def one_touch_status
    @user = User.find(session[:pre_2fa_auth_user_id])
    session[:user_id] = @user.approved? ? @user.id : nil
    render plain: @user.authy_status
  end

  def send_token
    @user = User.find(session[:pre_2fa_auth_user_id])
    Authy::API.request_sms(id: @user.authy_id)
    render plain: 'sending token'
  end

  def verify
    @user = User.find(session[:pre_2fa_auth_user_id])
    token = Authy::API.verify(id: @user.authy_id, token: params[:token])
    if token.ok?
      session[:user_id] = @user.id
      session[:pre_2fa_auth_user_id] = nil
      redirect_to account_path
    else
      flash.now[:danger] = "Incorrect code, please try again"
      redirect_to new_session_path
    end
  end

  # Authenticate that all requests to our public-facing callback is
  # coming from Authy. Adapted from the example at 
  # https://docs.authy.com/new_doc/authy_onetouch_api#authenticating-callbacks-from-authy-onetouch
  private
  def authenticate_authy_request
    url = request.url
    raw_params = JSON.parse(request.raw_post)
    nonce = request.headers["X-Authy-Signature-Nonce"]
    sorted_params = (Hash[raw_params.sort]).to_query

    # data format of Authy digest
    data = nonce + "|" + request.method + "|" + url + "|" + sorted_params

    digest = OpenSSL::HMAC.digest('sha256', Authy.api_key, data)
    digest_in_base64 = Base64.encode64(digest)

    theirs = (request.headers['X-Authy-Signature']).strip
    mine = digest_in_base64.strip

    unless theirs == mine
      render plain: 'invalid request signature'
    end
  end
end