Two-Factor Authentication with Authy, Ruby and Sinatra

This Sinatra sample application is an example of 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 first 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 via 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.

Configure Authy

If you haven't configured Authy already now is the time to sign up for Authy. Create your first application naming it as 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 an environment variable.

Loading Code Samples...
Language
module Routes
  module Signup
    def self.registered(app)
      app.get '/signup' do
        haml :signup
      end

      app.post '/signup' do
        password_salt, password_hash = hash_password(params[:password])
        user = User.create!(
          username:      params[:username],
          email:         params[:email],
          password_salt: password_salt,
          password_hash: password_hash,
          country_code:  params[:country_code],
          phone_number:  params[:phone_number]
        )

        Authy.api_key = ENV['AUTHY_API_KEY']
        authy = Authy::API.register_user(
          email: user.email,
          cellphone: user.phone_number,
          country_code: user.country_code
        )

        user.update!(authy_id: authy.id)
        init_session!(user.id)

        redirect '/protected'
      end
    end
  end
end
routes/signup.rb
Configure Authy

routes/signup.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 store our new user into the database and will register the user with Authy.

All Authy needs to get a user set up for your application is the 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
module Routes
  module Signup
    def self.registered(app)
      app.get '/signup' do
        haml :signup
      end

      app.post '/signup' do
        password_salt, password_hash = hash_password(params[:password])
        user = User.create!(
          username:      params[:username],
          email:         params[:email],
          password_salt: password_salt,
          password_hash: password_hash,
          country_code:  params[:country_code],
          phone_number:  params[:phone_number]
        )

        Authy.api_key = ENV['AUTHY_API_KEY']
        authy = Authy::API.register_user(
          email: user.email,
          cellphone: user.phone_number,
          country_code: user.country_code
        )

        user.update!(authy_id: authy.id)
        init_session!(user.id)

        redirect '/protected'
      end
    end
  end
end
routes/signup.rb
Register a user with Authy

routes/signup.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 authentication. Let's take a look at OneTouch verification first.

Authy OneTouch Approval

OneTouch works like this:

  • We attempt to send a OneTouch Approval Request to the user.
  • 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.
Loading Code Samples...
Language
module Routes
  module Sessions
    def self.registered(app)
      app.get '/login' do
        haml :login
      end

      app.post '/login' do
        user = User.first(email: params[:email])
        if user && valid_password?(params[:password], user.password_hash)
          Authy.api_key = ENV['AUTHY_API_KEY']
          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)

          pre_init_session!(user.id)

          status.to_s
        else
          'unauthorized'
        end
      end

      app.get '/logout' do
        destroy_session!
        redirect '/login'
      end
    end
  end
end
routes/sessions.rb
Log in with Authy OneTouch

routes/sessions.rb

In the next steps we'll look at how we handle cases where the user does not have OneTouch, or denies the login request.

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",

Once we send the request we need to update our user's authy_status based on the response.

Loading Code Samples...
Language
module Routes
  module Sessions
    def self.registered(app)
      app.get '/login' do
        haml :login
      end

      app.post '/login' do
        user = User.first(email: params[:email])
        if user && valid_password?(params[:password], user.password_hash)
          Authy.api_key = ENV['AUTHY_API_KEY']
          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)

          pre_init_session!(user.id)

          status.to_s
        else
          'unauthorized'
        end
      end

      app.get '/logout' do
        destroy_session!
        redirect '/login'
      end
    end
  end
end
routes/sessions.rb
Implement OneTouch Approval

routes/sessions.rb

Once we send the request we need to update our user's AuthyStatus 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
module Routes
  module Confirmation
    def self.registered(app)
      app.post '/authy/callback' do
        authenticate_request!(request)

        request.body.rewind
        params       = JSON.parse(request.body.read)
        authy_id     = params['authy_id']
        authy_status = params['status']

        begin
          user = User.first(authy_id: authy_id)
          user.update!(authy_status: authy_status)
        rescue => e
          puts e.message
        end

        'OK'
      end

      app.post '/authy/status' do
        user = User.first(id: current_user)
        user.authy_status.to_s
      end

      app.post '/confirm-login' do
        user = User.first(id: current_user)
        authy_status = user.authy_status

        user.update(authy_status: :unverified)

        if authy_status == :approved
          init_session!(user.id)
          redirect '/protected'
        else
          destroy_session!
          redirect '/login'
        end
      end

      app.post '/send-token' do
        user = User.first(id: current_user)
        Authy::API.request_sms(id: user.authy_id)
        'Token has been sent'
      end

      app.post '/verify-token' do
        user = User.first(id: current_user)
        token = Authy::API.verify(id: user.authy_id, token: params[:token])
        if token.ok?
          init_session!(user.id)
          redirect '/protected'
        else
          # 'Incorrect code, please try again'
          destroy_session!
          redirect '/login'
        end
      end
    end
  end
end
routes/confirmation.rb
Configure the OneTouch callback

routes/confirmation.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(event) {
        event.preventDefault();

        var data = $(event.currentTarget).serialize();
        authyVerification(data);
    });

    var authyVerification = function (data) {
        $.post("/login", data, function (result) {
            resultActions[result]();
        });
    };

    var resultActions = {
        onetouch: function() {
            $("#authy-modal").modal({ backdrop: "static" }, "show");
            $(".auth-token").hide();
            $(".auth-onetouch").fadeIn();
            monitorOneTouchStatus();
        },

        sms: function () {
            $("#authy-modal").modal({ backdrop: "static" }, "show");
            $(".auth-onetouch").hide();
            $(".auth-token").fadeIn();
            requestAuthyToken();
        },

        unauthorized: function () {
            $("#error-message").text("The email and password you entered don't match.");
        }
    };

    var monitorOneTouchStatus = function () {
        $.post("/authy/status")
            .done(function (data) {
                if (data === "approved" || data === "denied") {
                    $("#confirm-login").submit();
                } else {
                    setTimeout(monitorOneTouchStatus, 2000);
                }
            });
    }

    var requestAuthyToken = function () {
        $.post("/authy/request-token")
            .done(function (data) {
                $("#authy-token-label").text(data);
            });
    }

    $("#logout").click(function() {
        $("#logout-form").submit();
    });
});
public/javascripts/app.js
Poll the server until we see the result of the Authy OneTouch login

public/javascripts/app.js

Finally, we can confirm the login.

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
module Routes
  module Confirmation
    def self.registered(app)
      app.post '/authy/callback' do
        authenticate_request!(request)

        request.body.rewind
        params       = JSON.parse(request.body.read)
        authy_id     = params['authy_id']
        authy_status = params['status']

        begin
          user = User.first(authy_id: authy_id)
          user.update!(authy_status: authy_status)
        rescue => e
          puts e.message
        end

        'OK'
      end

      app.post '/authy/status' do
        user = User.first(id: current_user)
        user.authy_status.to_s
      end

      app.post '/confirm-login' do
        user = User.first(id: current_user)
        authy_status = user.authy_status

        user.update(authy_status: :unverified)

        if authy_status == :approved
          init_session!(user.id)
          redirect '/protected'
        else
          destroy_session!
          redirect '/login'
        end
      end

      app.post '/send-token' do
        user = User.first(id: current_user)
        Authy::API.request_sms(id: user.authy_id)
        'Token has been sent'
      end

      app.post '/verify-token' do
        user = User.first(id: current_user)
        token = Authy::API.verify(id: user.authy_id, token: params[:token])
        if token.ok?
          init_session!(user.id)
          redirect '/protected'
        else
          # 'Incorrect code, please try again'
          destroy_session!
          redirect '/login'
        end
      end
    end
  end
end
routes/confirmation.rb
Redirect user to the right page based based on authentication status

routes/confirmation.rb

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

Where to Next?

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

SMS and MMS Notifications

Faster than e-mail and less likely to get blocked, text messages are great for timely alerts and notifications. Learn how to send out SMS (and MMS) notifications to a list of server administrators.

Click-To-Call

Click-to-call enables your company to convert web traffic into phone calls with the click of a button

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
David Prothero
Agustin Camino
Andrew Baker

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...
module Routes
  module Signup
    def self.registered(app)
      app.get '/signup' do
        haml :signup
      end

      app.post '/signup' do
        password_salt, password_hash = hash_password(params[:password])
        user = User.create!(
          username:      params[:username],
          email:         params[:email],
          password_salt: password_salt,
          password_hash: password_hash,
          country_code:  params[:country_code],
          phone_number:  params[:phone_number]
        )

        Authy.api_key = ENV['AUTHY_API_KEY']
        authy = Authy::API.register_user(
          email: user.email,
          cellphone: user.phone_number,
          country_code: user.country_code
        )

        user.update!(authy_id: authy.id)
        init_session!(user.id)

        redirect '/protected'
      end
    end
  end
end
module Routes
  module Signup
    def self.registered(app)
      app.get '/signup' do
        haml :signup
      end

      app.post '/signup' do
        password_salt, password_hash = hash_password(params[:password])
        user = User.create!(
          username:      params[:username],
          email:         params[:email],
          password_salt: password_salt,
          password_hash: password_hash,
          country_code:  params[:country_code],
          phone_number:  params[:phone_number]
        )

        Authy.api_key = ENV['AUTHY_API_KEY']
        authy = Authy::API.register_user(
          email: user.email,
          cellphone: user.phone_number,
          country_code: user.country_code
        )

        user.update!(authy_id: authy.id)
        init_session!(user.id)

        redirect '/protected'
      end
    end
  end
end
module Routes
  module Sessions
    def self.registered(app)
      app.get '/login' do
        haml :login
      end

      app.post '/login' do
        user = User.first(email: params[:email])
        if user && valid_password?(params[:password], user.password_hash)
          Authy.api_key = ENV['AUTHY_API_KEY']
          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)

          pre_init_session!(user.id)

          status.to_s
        else
          'unauthorized'
        end
      end

      app.get '/logout' do
        destroy_session!
        redirect '/login'
      end
    end
  end
end
module Routes
  module Sessions
    def self.registered(app)
      app.get '/login' do
        haml :login
      end

      app.post '/login' do
        user = User.first(email: params[:email])
        if user && valid_password?(params[:password], user.password_hash)
          Authy.api_key = ENV['AUTHY_API_KEY']
          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)

          pre_init_session!(user.id)

          status.to_s
        else
          'unauthorized'
        end
      end

      app.get '/logout' do
        destroy_session!
        redirect '/login'
      end
    end
  end
end
module Routes
  module Confirmation
    def self.registered(app)
      app.post '/authy/callback' do
        authenticate_request!(request)

        request.body.rewind
        params       = JSON.parse(request.body.read)
        authy_id     = params['authy_id']
        authy_status = params['status']

        begin
          user = User.first(authy_id: authy_id)
          user.update!(authy_status: authy_status)
        rescue => e
          puts e.message
        end

        'OK'
      end

      app.post '/authy/status' do
        user = User.first(id: current_user)
        user.authy_status.to_s
      end

      app.post '/confirm-login' do
        user = User.first(id: current_user)
        authy_status = user.authy_status

        user.update(authy_status: :unverified)

        if authy_status == :approved
          init_session!(user.id)
          redirect '/protected'
        else
          destroy_session!
          redirect '/login'
        end
      end

      app.post '/send-token' do
        user = User.first(id: current_user)
        Authy::API.request_sms(id: user.authy_id)
        'Token has been sent'
      end

      app.post '/verify-token' do
        user = User.first(id: current_user)
        token = Authy::API.verify(id: user.authy_id, token: params[:token])
        if token.ok?
          init_session!(user.id)
          redirect '/protected'
        else
          # 'Incorrect code, please try again'
          destroy_session!
          redirect '/login'
        end
      end
    end
  end
end
$(document).ready(function() {
    $("#login-form").submit(function(event) {
        event.preventDefault();

        var data = $(event.currentTarget).serialize();
        authyVerification(data);
    });

    var authyVerification = function (data) {
        $.post("/login", data, function (result) {
            resultActions[result]();
        });
    };

    var resultActions = {
        onetouch: function() {
            $("#authy-modal").modal({ backdrop: "static" }, "show");
            $(".auth-token").hide();
            $(".auth-onetouch").fadeIn();
            monitorOneTouchStatus();
        },

        sms: function () {
            $("#authy-modal").modal({ backdrop: "static" }, "show");
            $(".auth-onetouch").hide();
            $(".auth-token").fadeIn();
            requestAuthyToken();
        },

        unauthorized: function () {
            $("#error-message").text("The email and password you entered don't match.");
        }
    };

    var monitorOneTouchStatus = function () {
        $.post("/authy/status")
            .done(function (data) {
                if (data === "approved" || data === "denied") {
                    $("#confirm-login").submit();
                } else {
                    setTimeout(monitorOneTouchStatus, 2000);
                }
            });
    }

    var requestAuthyToken = function () {
        $.post("/authy/request-token")
            .done(function (data) {
                $("#authy-token-label").text(data);
            });
    }

    $("#logout").click(function() {
        $("#logout-form").submit();
    });
});
module Routes
  module Confirmation
    def self.registered(app)
      app.post '/authy/callback' do
        authenticate_request!(request)

        request.body.rewind
        params       = JSON.parse(request.body.read)
        authy_id     = params['authy_id']
        authy_status = params['status']

        begin
          user = User.first(authy_id: authy_id)
          user.update!(authy_status: authy_status)
        rescue => e
          puts e.message
        end

        'OK'
      end

      app.post '/authy/status' do
        user = User.first(id: current_user)
        user.authy_status.to_s
      end

      app.post '/confirm-login' do
        user = User.first(id: current_user)
        authy_status = user.authy_status

        user.update(authy_status: :unverified)

        if authy_status == :approved
          init_session!(user.id)
          redirect '/protected'
        else
          destroy_session!
          redirect '/login'
        end
      end

      app.post '/send-token' do
        user = User.first(id: current_user)
        Authy::API.request_sms(id: user.authy_id)
        'Token has been sent'
      end

      app.post '/verify-token' do
        user = User.first(id: current_user)
        token = Authy::API.verify(id: user.authy_id, token: params[:token])
        if token.ok?
          init_session!(user.id)
          redirect '/protected'
        else
          # 'Incorrect code, please try again'
          destroy_session!
          redirect '/login'
        end
      end
    end
  end
end