How to Add Two-Factor Authentication to a Ruby Application with Plivo

Two-factor authentication (2FA) can play a key role in securing your applications against password data breaches. Authentication with a one-time password (OTP) delivered to your users over SMS is an effective approach to implementing two-factor authentication. Plivo’s premium direct routes guarantee the highest possible delivery rates and the shortest possible delivery times for your 2FA SMS messages. In this blog post, we walk you through a sample implementation of 2FA using the Plivo SMS platform and PHLO, our visual workflow builder.


Before you get started, you’ll need:

  • A Plivo account — sign up for one for free if you don’t have one already.
  • An SMS-enabled Plivo phone number to send messages to the US and Canada. To search for and rent an available number, go to Phone Numbers > Buy Numbers on the Plivo console. Buy a New Plivo Number

Create a PHLO to send OTP via SMS

PHLO lets you construct your entire use case and build and deploy workflows visually. With PHLO, you pay only for calls you make and receive, and building with PHLO is free.

To get started, visit PHLO in the Plivo console and click on Create New PHLO. A pop-up window gives you a list of prebuilt templates to start with. Choose Two-Factor Authentication and click Create Application to create a PHLO with the prebuilt components to build a workflow that can manage sending the OTP via SMS, with failover to use a phone call to deliver the OTP as a text-to-speech (TTS) message.

Use the PHLO in a Ruby application

We have a demo application available for this in our GitHub repository that you can clone to see how the implementation works.

  • Clone the repository from GitHub.
    $ git clone
  • Change your working directory to 2fa-ruby-demo.
    $ cd 2fa-ruby-demo
  • Install the dependencies using the Gemfile file.
    $ bundle install
  • Edit the config.yaml file. Replace the PLIVO_AUTH_ID, PLIVO_AUTH_TOKEN, PLIVO_NUMBER, and PHLO_ID placeholders with your own values.
    Configuration file

Note: Enter your phone number in E.164 format.

Generate the OTP

Generate an exclusive six-digit authentication code. To create the OTP, use the time-based OTP generation algorithm. Here’s how it’s done in ruby.

code = rand(999_999)

Send OTP via SMS or a phone call

A single function helps us to trigger the PHLO to send SMS messages and make calls; the rest of the work is done by PHLO. Use the mode argument to tell PHLO whether to trigger a call or an SMS message by passing the value “sms” or “call.”

 def initiate_phlo(dst_number, mode)
    code = rand(999_999)
      phlo = @phloclient.phlo.get(@phlo_id)
      # parameters set in PHLO - params
      params = {
        from: @app_number,
        to: dst_number,
        otp: code,
        mode: mode
    rescue PlivoRESTError => e
      puts 'Exception: ' + e.message

Verify the OTP

After the user enters the OTP they received on their handset, this ruby code verifies it.

get '/verify/:number' do
  number = params['number']
  # verify(number) accepts a number and initiates verification for it.
  code = if config['phlo_id'].nil?
           twofactor.send_verification_code_sms(number, 'Your verification code is __code__. Code will expire in 1 minute.')
           twofactor.initiate_phlo(number, 'sms')
  r.setex('number:%s:code' % number, 60, code) # Verification code is valid for 1 min
  content_type :json
  { status: 'success', message: 'verification initiated' }.to_json


To run the application, start Redis using the redis-server command. Build and Run the app using the command $ ruby app.rb. You can use the URL http://localhost:3000/ to run the sample application in your browser.

On the browser page, choose your country and enter your mobile number, then click on Send Verification Code. Check your mobile phone — you should get an SMS message with an OTP code. Enter the code in the browser form and click Verify, and the application will confirm that you’re verified.

What if you don’t get the SMS message you were expecting, or you wait too long to enter the value you received? The application gives you a link so you can use a phone call as a fallback OTP channel. Click on “Didn’t receive sms? Call me.” You should then receive a call, and when you answer it, you’ll hear a text-to-speech message that gives you an OTP code, which you can use in the form for verification.

Simple and reliable

Edit the sample application to see how simple it was to code. Our simple APIs work in tandem with our comprehensive global network. Plivo’s premium direct routes guarantee the highest possible delivery rates and the shortest possible delivery times for your 2FA SMS and voice messages. See for yourself — sign up for a free trial account.

comments powered by Disqus

By submitting this form, you agree we may contact you in the manner described in our Privacy Policy.