As of November 2022, Twilio no longer provides support for Authy SMS/Voice-only customers. Customers who were also using Authy TOTP or Push prior to March 1, 2023 are still supported. The Authy API is now closed to new customers and will be fully deprecated in the future.
For new development, we encourage you to use the Verify v2 API.
Existing customers will not be impacted at this time until Authy API has reached End of Life. For more information about migration, see Migrating from Authy to Verify for SMS.
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:
See how VMware uses Authy 2FA to secure their enterprise mobility management solution.
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.
Once we have an Authy API key we register it as an environment variable.
routes/signup.rb
1module Routes2module Signup3def self.registered(app)4app.get '/signup' do5haml :signup6end78app.post '/signup' do9password_salt, password_hash = hash_password(params[:password])10user = User.create!(11username: params[:username],12email: params[:email],13password_salt: password_salt,14password_hash: password_hash,15country_code: params[:country_code],16phone_number: params[:phone_number]17)1819Authy.api_key = ENV['AUTHY_API_KEY']20authy = Authy::API.register_user(21email: user.email,22cellphone: user.phone_number,23country_code: user.country_code24)2526user.update!(authy_id: authy.id)27init_session!(user.id)2829redirect '/protected'30end31end32end33end34
Let's take a look at how we 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.
routes/signup.rb
1module Routes2module Signup3def self.registered(app)4app.get '/signup' do5haml :signup6end78app.post '/signup' do9password_salt, password_hash = hash_password(params[:password])10user = User.create!(11username: params[:username],12email: params[:email],13password_salt: password_salt,14password_hash: password_hash,15country_code: params[:country_code],16phone_number: params[:phone_number]17)1819Authy.api_key = ENV['AUTHY_API_KEY']20authy = Authy::API.register_user(21email: user.email,22cellphone: user.phone_number,23country_code: user.country_code24)2526user.update!(authy_id: authy.id)27init_session!(user.id)2829redirect '/protected'30end31end32end33end34
Having registered our user with Authy, we then can use Authy's OneTouch feature to log them in.
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.
OneTouch works like this:
success
message back.POST
request to our app with an approved
status.routes/sessions.rb
1require 'haml'23module Routes4module Sessions5def self.registered(app)6app.get '/login' do7haml(:login)8end910app.post '/login' do11user = User.first(email: params[:email])12if user && valid_password?(params[:password], user.password_hash)13Authy.api_key = ENV['AUTHY_API_KEY']14user_status = Authy::API.user_status(id: user.authy_id)15puts user_status16required_devices = ['iphone', 'android']17registered_devices = user_status['status']['devices']1819if user_status['status']['registered'] \20and (required_devices & registered_devices)21Authy::OneTouch.send_approval_request(22id: user.authy_id,23message: 'Request to Login to Twilio demo app',24details: { 'Email Address' => user.email }25)2627status = :onetouch28else29Authy::API.request_sms(id: user.authy_id)30status = :sms31end32user.update!(authy_status: status)3334pre_init_session!(user.id)3536status.to_s37else38'unauthorized'39end40end4142app.get '/logout' do43destroy_session!44redirect '/login'45end46end47end48end49
In the next steps we'll look at how we handle cases where the user does not have OneTouch, or denies the login 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 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.
1"message" => "Request to Send Money to Jarod's vault",2"details['Request From']" => "Jarod",3"details['Amount Request']" => "1,000,000",4"details['Currency']" => "Galleons",5
Once we send the request we need to update our user's authy_status
based on the response.
routes/sessions.rb
1require 'haml'23module Routes4module Sessions5def self.registered(app)6app.get '/login' do7haml(:login)8end910app.post '/login' do11user = User.first(email: params[:email])12if user && valid_password?(params[:password], user.password_hash)13Authy.api_key = ENV['AUTHY_API_KEY']14user_status = Authy::API.user_status(id: user.authy_id)15puts user_status16required_devices = ['iphone', 'android']17registered_devices = user_status['status']['devices']1819if user_status['status']['registered'] \20and (required_devices & registered_devices)21Authy::OneTouch.send_approval_request(22id: user.authy_id,23message: 'Request to Login to Twilio demo app',24details: { 'Email Address' => user.email }25)2627status = :onetouch28else29Authy::API.request_sms(id: user.authy_id)30status = :sms31end32user.update!(authy_status: status)3334pre_init_session!(user.id)3536status.to_s37else38'unauthorized'39end40end4142app.get '/logout' do43destroy_session!44redirect '/login'45end46end47end48end49
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.
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.
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 just update the authy_status
on the user.
routes/confirmation.rb
1module Routes2module Confirmation3def self.registered(app)4app.post '/authy/callback' do5authenticate_request!(request)67request.body.rewind8params = JSON.parse(request.body.read)9authy_id = params['authy_id']10authy_status = params['status']1112begin13user = User.first(authy_id: authy_id)14user.update!(authy_status: authy_status)15rescue => e16puts e.message17end1819'OK'20end2122app.post '/authy/status' do23user = User.first(id: current_user)24user.authy_status.to_s25end2627app.post '/confirm-login' do28user = User.first(id: current_user)29authy_status = user.authy_status3031user.update(authy_status: :unverified)3233if authy_status == :approved34init_session!(user.id)35redirect '/protected'36else37destroy_session!38redirect '/login'39end40end4142app.post '/send-token' do43user = User.first(id: current_user)44Authy::API.request_sms(id: user.authy_id)45'Token has been sent'46end4748app.post '/verify-token' do49user = User.first(id: current_user)50token = Authy::API.verify(id: user.authy_id, token: params[:token])51if token.ok?52init_session!(user.id)53redirect '/protected'54else55# 'Incorrect code, please try again'56destroy_session!57redirect '/login'58end59end60end61end62end63
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.
Scenario: The OneTouch callback URL provided by you is no longer active.
Action: We will disable the OneTouch callback after 3 consecutive HTTP error responses. We will also
How to enable OneTouch callback? You need to update the OneTouch callback endpoint, which will allow the OneTouch callback.
Visit the Twilio Console: Console > Authy > Applications > {ApplicationName} > Push Authentication > Webhooks > Endpoint/URL to update the Endpoint/URL with a valid OneTouch callback URL.
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.
public/javascripts/app.js
1$(document).ready(function() {2$("#login-form").submit(function(event) {3event.preventDefault();45var data = $(event.currentTarget).serialize();6authyVerification(data);7});89var authyVerification = function (data) {10$.post("/login", data, function (result) {11resultActions[result]();12});13};1415var resultActions = {16onetouch: function() {17$("#authy-modal").modal({ backdrop: "static" }, "show");18$(".auth-token").hide();19$(".auth-onetouch").fadeIn();20monitorOneTouchStatus();21},2223sms: function () {24$("#authy-modal").modal({ backdrop: "static" }, "show");25$(".auth-onetouch").hide();26$(".auth-token").fadeIn();27requestAuthyToken();28},2930unauthorized: function () {31$("#error-message").text("The email and password you entered don't match.");32}33};3435var monitorOneTouchStatus = function () {36$.post("/authy/status")37.done(function (data) {38if (data === "approved" || data === "denied") {39$("#confirm-login").submit();40} else {41setTimeout(monitorOneTouchStatus, 2000);42}43});44}4546var requestAuthyToken = function () {47$.post("/authy/request-token")48.done(function (data) {49$("#authy-token-label").text(data);50});51}5253$("#logout").click(function() {54$("#logout-form").submit();55});56});57
Finally, we can confirm the login.
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.
routes/confirmation.rb
1module Routes2module Confirmation3def self.registered(app)4app.post '/authy/callback' do5authenticate_request!(request)67request.body.rewind8params = JSON.parse(request.body.read)9authy_id = params['authy_id']10authy_status = params['status']1112begin13user = User.first(authy_id: authy_id)14user.update!(authy_status: authy_status)15rescue => e16puts e.message17end1819'OK'20end2122app.post '/authy/status' do23user = User.first(id: current_user)24user.authy_status.to_s25end2627app.post '/confirm-login' do28user = User.first(id: current_user)29authy_status = user.authy_status3031user.update(authy_status: :unverified)3233if authy_status == :approved34init_session!(user.id)35redirect '/protected'36else37destroy_session!38redirect '/login'39end40end4142app.post '/send-token' do43user = User.first(id: current_user)44Authy::API.request_sms(id: user.authy_id)45'Token has been sent'46end4748app.post '/verify-token' do49user = User.first(id: current_user)50token = Authy::API.verify(id: user.authy_id, token: params[:token])51if token.ok?52init_session!(user.id)53redirect '/protected'54else55# 'Incorrect code, please try again'56destroy_session!57redirect '/login'58end59end60end61end62end63
That's it! We've just implemented two-factor auth using three different methods and the latest Authy technology.
If you're a Ruby developer working with Twilio, you might enjoy these other tutorials:
Click-to-call enables your company to convert web traffic into phone calls with the click of a button.