Saturday, 3 June 2017

Twilio Phone Number authentication with Authy in Ruby on Rails.

Authy is a Twilio service that provides two factor authentication as an API, making it easy to secure users accounts. Using authy services we can authenticate users by their phone number. OTP will be send on phone number and it will be verified at the twilio end.


In Gemfile.

    # Use Authy for sending token
    gem 'authy'
    # Use Twilio to send confirmation message
    gem 'twilio-ruby'

We need an API key for Authy. You can get this from your Twilio account portal. Click the link to access the Authy dashboard.

If you don’t already have an Authy account, this will set one up for you. You will need to verify your email address and set up two factor authentication. Then you can create an application with Authy and this will give you your API key.

Create a new file authy.rb in config/initializers.

In authy.rb


    Authy.api_key = 'api_key'

    Authy.api_uri = 'https://api.authy.com/'

Now, we can start phone verification via sending a sms.

In sessions controller


     def send_otp

         response = Authy::PhoneVerification.start(via: "sms", country_code: 1, phone_number: "111-111-1111")

         render json: {response: response.message}, status: response.code

     end


    def verify_otp

        response = Authy::PhoneVerification.check(verification_code: "1234", country_code: 1, phone_number: "111-111-1111")

        if response.ok?

              # verification was successful

            end       

    end

In routes.rb


    resources :sessions do

        collection do

          post :send_otp

          post :verify_otp

        end

    end

1 comment: