Ruby on Rails Quickstart for Twilio Authy Two-factor Authentication

Adding Two-factor Authentication to your application is the easiest way to increase security and trust in your product without unnecessarily burdening your users. This quickstart guides you through building a Ruby and Ruby on Rails application that restricts access to a URL. Four Authy API channels are demoed: SMS, Voice, Soft Tokens and Push Notifications.

Ready to protect a tiny app from malicious hackers?

Sign Up For or Sign Into a Twilio Account

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

Create a New Authy Application

Once you are logged in, click through to the Authy Console. Click the red plus ('+') button to create a new Account Security application, and name it something memorable.

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

Account Security API Key

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

Setup the Authy Client on Your Device

This Two-factor Authentication demos two channels which require an installed Authy Client to test: Soft Tokens and Push Notifications. While SMS and Voice channels will work without the client, to try out all four authentication channels download and install Authy Client for Desktop or Mobile:

Clone and Setup the Application

Clone our repository locally, then enter the directory. Install all of the necessary ruby modules:

bundle install

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

It will be loaded when the application begins.

Loading Code Samples...
Language
ACCOUNT_SECURITY_API_KEY: YOUR APP_KEY
Enter the API Key from the Authy console.
Add Your Application API Key

Enter the API Key from the Authy console.

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

./bin/rails server

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

Try the Ruby on Rails Authy Two-Factor Demo

With your phone (optionally with the Authy client installed) nearby, open a new browser tab and navigate to http://localhost:3000/register/

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

Now visit http://localhost:3000/login/ and login. You'll be presented with a happy screen:

Token Verification Page

If your phone has the Authy Client installed, you can immediately enter a Soft Token from the client to Verify. Additionally, you can try a Push Authentication simply by pushing the labeled button.

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

Loading Code Samples...
Language
class Api::TwofaController < ApplicationController
  def sms()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    response = Authy::API.request_sms(id: user.authy_id)

    if ! response.ok?
      render json: { err: 'Error requesting SMS token' }, status: :internal_server_error and return
    end

    render json: response, status: :ok
  end

  def voice()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    response = Authy::API.request_phone_call(id: user.authy_id)

    if ! response.ok?
      render json: { err: 'Error requesting Phone call token' }, status: :internal_server_error and return
    end

    render json: response, status: :ok
  end

  def verify()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    response = Authy::API.verify(:id => user.authy_id, :token => params[:token])

    if ! response.ok?
      render json: { err: 'Verify Token Error' }, status: :internal_server_error and return
    end

    session[:authy] = true
    render json: response, status: :ok
  end

  def onetouchstatus()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    status = Authy::OneTouch.approval_request_status({uuid: session[:uuid]})

    if ! status.ok?
      render json: { err: 'One Touch Status Error' }, status: :internal_server_error and return
    end

    if status['approval_request']['approval_request'] == 'approved'
      session.delete(:uuid) || session.delete('uuid')
      session[:authy] = true
    end

    render json: {body: status}, status: :ok
  end

  def onetouch()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    one_touch = Authy::OneTouch.send_approval_request(
      id: user.authy_id,
      message: 'Login requested for Account Security account.',
      details: {
        AuthyID: user.authy_id,
        Username: user.username,
        Location: 'San Francisco, CA',
        Reason: 'Demo by Account Security'
      },
      hidden_details: { test: "This is a" }
    )

    if ! one_touch.ok?
      render json: { err: 'Create Push Error' }, status: :internal_server_error and return
    end

    session[:uuid] = one_touch.approval_request['uuid']

    render json: one_touch, status: :ok
  end
end
Two-Factor Authentication Channels

And there you go, Authy two-factor authentication is on and your Rails app is protected!

What's Next?

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

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

 

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.

Loading Code Samples...
ACCOUNT_SECURITY_API_KEY: YOUR APP_KEY
class Api::TwofaController < ApplicationController
  def sms()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    response = Authy::API.request_sms(id: user.authy_id)

    if ! response.ok?
      render json: { err: 'Error requesting SMS token' }, status: :internal_server_error and return
    end

    render json: response, status: :ok
  end

  def voice()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    response = Authy::API.request_phone_call(id: user.authy_id)

    if ! response.ok?
      render json: { err: 'Error requesting Phone call token' }, status: :internal_server_error and return
    end

    render json: response, status: :ok
  end

  def verify()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    response = Authy::API.verify(:id => user.authy_id, :token => params[:token])

    if ! response.ok?
      render json: { err: 'Verify Token Error' }, status: :internal_server_error and return
    end

    session[:authy] = true
    render json: response, status: :ok
  end

  def onetouchstatus()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    status = Authy::OneTouch.approval_request_status({uuid: session[:uuid]})

    if ! status.ok?
      render json: { err: 'One Touch Status Error' }, status: :internal_server_error and return
    end

    if status['approval_request']['approval_request'] == 'approved'
      session.delete(:uuid) || session.delete('uuid')
      session[:authy] = true
    end

    render json: {body: status}, status: :ok
  end

  def onetouch()
    user = User.find_by(username: session[:username])

    if ! user
      render json: { err: 'Username Not Found' }, status: :internal_server_error and return
    end

    one_touch = Authy::OneTouch.send_approval_request(
      id: user.authy_id,
      message: 'Login requested for Account Security account.',
      details: {
        AuthyID: user.authy_id,
        Username: user.username,
        Location: 'San Francisco, CA',
        Reason: 'Demo by Account Security'
      },
      hidden_details: { test: "This is a" }
    )

    if ! one_touch.ok?
      render json: { err: 'Create Push Error' }, status: :internal_server_error and return
    end

    session[:uuid] = one_touch.approval_request['uuid']

    render json: one_touch, status: :ok
  end
end