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.
Adding Two-Factor Authentication (2FA) to your web application increases the security of your user's data by requiring something your user has to be present for step-up transactions, log-ins, and other sensitive actions. Multi-factor authentication determines the identity of a user by validating once by logging into the app, and then by validating their mobile device.
This PHP Laravel sample application is an example of a typical login flow using Two-Factor Authentication. To run this sample app yourself, download the code and follow the instructions on GitHub.
For the second factor, we will validate that the user has their mobile phone by either:
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 can register it as an environment variable.
.env.example
1APP_ENV=local2APP_DEBUG=true3APP_KEY=ufxhZiQcKxi1eHVmGq8MwfAcRgZHJ1Qq45DB_HOST=localhost6DB_DATABASE=authy_laravel7DB_USERNAME=your_db_username8DB_PASSWORD=your_db_password910AUTHY_API_KEY=your_token
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 save our new user to the database and will register the user with Authy.
In order to set up your application, Authy only needs the user's 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.
app/User.php
1<?php namespace App;23use Illuminate\Auth\Authenticatable;4use Illuminate\Database\Eloquent\Model;5use Illuminate\Auth\Passwords\CanResetPassword;6use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;7use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;89class User extends Model implements AuthenticatableContract, CanResetPasswordContract10{1112use Authenticatable, CanResetPassword;1314/**15* The database table used by the model.16*17* @var string18*/19protected $table = 'users';2021/**22* The attributes that are mass assignable.23*24* @var array25*/26protected $fillable = ['name', 'email', 'password', 'phone_number', 'country_code'];2728/**29* The attributes excluded from the model's JSON form.30*31* @var array32*/33protected $hidden = ['password', 'remember_token', 'authy_status', 'authy_id'];343536/**37* @param $authy_id string38*/39public function updateAuthyId($authy_id) {40if($this->authy_id != $authy_id) {41$this->authy_id = $authy_id;42$this->save();43}44}4546/**47* @param $status string48*/49public function updateVerificationStatus($status) {50// reset oneTouch status51if ($this->authy_status != $status) {52$this->authy_status = $status;53$this->save();54}55}5657public function updateOneTouchUuid($uuid) {58if ($this->authy_one_touch_uuid != $uuid) {59$this->authy_one_touch_uuid = $uuid;60$this->save();61}62}63}64
When a User attempts to log in to our website, we will ask them for a second form of identification. Let's take a look at Authy's OneTouch verification first.
OneTouch works like this:
POST
request to our app with an approved status.app/Http/Controllers/Auth/AuthController.php
1<?php namespace App\Http\Controllers\Auth;23use App\Authy\Service;4use App\OneTouch;5use Auth;6use Session;7use App\User;8use App\Http\Controllers\Controller;9use Illuminate\Http\Request;10use Illuminate\Contracts\Auth\Guard;11use Illuminate\Contracts\Auth\Registrar;12use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;13use function Stringy\create;141516class AuthController extends Controller17{1819/*20|--------------------------------------------------------------------------21| Registration & Login Controller22|--------------------------------------------------------------------------23|24| This controller handles the registration of new users, as well as the25| authentication of existing users. By default, this controller uses26| a simple trait to add these behaviors. Why don't you explore it?27|28*/2930use AuthenticatesAndRegistersUsers;3132/**33* Create a new authentication controller instance.34*35* @param \Illuminate\Contracts\Auth\Guard $auth36* @param \Illuminate\Contracts\Auth\Registrar $registrar37* @param \App\Authy\Service $authy38*/39public function __construct(Guard $auth, Registrar $registrar, Service $authy)40{41$this->auth = $auth;42$this->registrar = $registrar;43$this->authy = $authy;4445$this->middleware('guest', ['except' => 'getLogout']);46}4748public function postLogin(Request $request)49{50$credentials = $request->only('email', 'password');51if (Auth::validate($credentials)) {52$user = User::where('email', '=', $request->input('email'))->firstOrFail();5354Session::set('password_validated', true);55Session::set('id', $user->id);5657if ($this->authy->verifyUserStatus($user->authy_id)->registered) {58$uuid = $this->authy->sendOneTouch($user->authy_id, 'Request to Login to Twilio demo app');5960OneTouch::create(['uuid' => $uuid]);6162Session::set('one_touch_uuid', $uuid);6364return response()->json(['status' => 'ok']);65} else66return response()->json(['status' => 'verify']);6768} else {69return response()->json(['status' => 'failed',70'message' => 'The email and password combination you entered is incorrect.']);71}72}7374public function getTwoFactor()75{76$message = Session::get('message');7778return view('auth/two-factor', ['message' => $message]);79}8081public function postTwoFactor(Request $request)82{83if (!Session::get('password_validated') || !Session::get('id')) {84return redirect('/auth/login');85}8687if (isset($_POST['token'])) {88$user = User::find(Session::get('id'));89if ($this->authy->verifyToken($user->authy_id, $request->input('token'))) {90Auth::login($user);91return redirect()->intended('/home');92} else {93return redirect('/auth/two-factor')->withErrors([94'token' => 'The token you entered is incorrect',95]);96}97}98}99100public function postRegister(Request $request)101{102$validator = $this->registrar->validator($request->all());103if ($validator->fails()) {104$this->throwValidationException(105$request, $validator106);107}108$user = $this->registrar->create($request->all());109110Session::set('password_validated', true);111Session::set('id', $user->id);112113$authy_id = $this->authy->register($user->email, $user->phone_number, $user->country_code);114115$user->updateAuthyId($authy_id);116117if ($this->authy->verifyUserStatus($authy_id)->registered)118$message = "Open Authy app in your phone to see the verification code";119else {120$this->authy->sendToken($authy_id);121$message = "You will receive an SMS with the verification code";122}123124return redirect('/auth/two-factor')->with('message', $message);125}126}127
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 won'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$params = array(2'message' => "Request to send money to Jarod's vault",3'details[From]' => "Jarod",4'details[Amount]' => "1,000,000",5'details[Currency]' => "Galleons",6)7
Once we send the request we need to update our User's authy_status
based on the response.
app/User.php
1<?php namespace App;23use Illuminate\Auth\Authenticatable;4use Illuminate\Database\Eloquent\Model;5use Illuminate\Auth\Passwords\CanResetPassword;6use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;7use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;89class User extends Model implements AuthenticatableContract, CanResetPasswordContract10{1112use Authenticatable, CanResetPassword;1314/**15* The database table used by the model.16*17* @var string18*/19protected $table = 'users';2021/**22* The attributes that are mass assignable.23*24* @var array25*/26protected $fillable = ['name', 'email', 'password', 'phone_number', 'country_code'];2728/**29* The attributes excluded from the model's JSON form.30*31* @var array32*/33protected $hidden = ['password', 'remember_token', 'authy_status', 'authy_id'];343536/**37* @param $authy_id string38*/39public function updateAuthyId($authy_id) {40if($this->authy_id != $authy_id) {41$this->authy_id = $authy_id;42$this->save();43}44}4546/**47* @param $status string48*/49public function updateVerificationStatus($status) {50// reset oneTouch status51if ($this->authy_status != $status) {52$this->authy_status = $status;53$this->save();54}55}5657public function updateOneTouchUuid($uuid) {58if ($this->authy_one_touch_uuid != $uuid) {59$this->authy_one_touch_uuid = $uuid;60$this->save();61}62}63}64
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.
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.
app/Http/Controllers/Auth/AuthyController.php
1<?php namespace App\Http\Controllers\Auth;23use App\OneTouch;4use Auth;5use Session;6use App\User;7use App\Http\Controllers\Controller;8use Illuminate\Http\Request;910class AuthyController extends Controller11{12/**13* Create a new controller instance.14*15* @return void16*/17public function __construct()18{19$this->middleware('guest');20}2122/**23* Check One Touch authorization status24*25* @param Request $request26* @return \Illuminate\Http\JsonResponse27*/28public function status(Request $request)29{30$oneTouch = OneTouch::where('uuid', '=', Session::get('one_touch_uuid'))->firstOrFail();31$status = $oneTouch->status;32if ($status == 'approved') {33Auth::login(User::find(Session::get('id')));34}35return response()->json(['status' => $status]);36}3738/**39* Public webhook for Authy40*41* @param Request $request42* @return string43*/44public function callback(Request $request)45{46$uuid = $request->input('uuid');47$oneTouch = OneTouch::where('uuid', '=', $uuid)->first();48if ($oneTouch != null) {49$oneTouch->status = $request->input('status');50$oneTouch->save();51return "ok";52}53return "invalid uuid: $uuid";54}5556}57
Let's take a look at the client-side code that will be handling this.
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/js/sessions.js
1$(document).ready(function() {2console.log('loaded');3$('#login-form').submit(function(e) {4e.preventDefault();5formData = $(e.currentTarget).serialize();6attemptOneTouchVerification(formData);7});89var attemptOneTouchVerification = function(form) {10$('#ajax-error').addClass('hidden');11$.post( "/auth/login", form, function(data) {12if (data.status === 'ok') {13$('#authy-modal').modal({backdrop:'static'},'show');14$('.auth-ot').fadeIn();15checkForOneTouch();16} else if (data.status === 'verify') {17$('#authy-modal').modal({backdrop:'static'},'show');18$('.auth-token').fadeIn()19} else if (data.status === 'failed') {20$('#ajax-error').html(data.message);21$('#ajax-error').removeClass('hidden');22}23});24};2526var checkForOneTouch = function() {27$.get("/authy/status", function (data) {28if (data.status === 'approved') {29window.location.href = "/home";30} else if (data.status === 'denied') {31showTokenForm();32triggerSMSToken();33} else {34setTimeout(checkForOneTouch, 5000);35}36});37};3839var showTokenForm = function() {40$('.auth-ot').fadeOut(function() {41$('.auth-token').fadeIn('slow')42})43};4445var triggerSMSToken = function() {46$.get("/authy/send_token")47};48});49
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.
app/Http/Controllers/Auth/AuthyController.php
1<?php namespace App\Http\Controllers\Auth;23use App\OneTouch;4use Auth;5use Session;6use App\User;7use App\Http\Controllers\Controller;8use Illuminate\Http\Request;910class AuthyController extends Controller11{12/**13* Create a new controller instance.14*15* @return void16*/17public function __construct()18{19$this->middleware('guest');20}2122/**23* Check One Touch authorization status24*25* @param Request $request26* @return \Illuminate\Http\JsonResponse27*/28public function status(Request $request)29{30$oneTouch = OneTouch::where('uuid', '=', Session::get('one_touch_uuid'))->firstOrFail();31$status = $oneTouch->status;32if ($status == 'approved') {33Auth::login(User::find(Session::get('id')));34}35return response()->json(['status' => $status]);36}3738/**39* Public webhook for Authy40*41* @param Request $request42* @return string43*/44public function callback(Request $request)45{46$uuid = $request->input('uuid');47$oneTouch = OneTouch::where('uuid', '=', $uuid)->first();48if ($oneTouch != null) {49$oneTouch->status = $request->input('status');50$oneTouch->save();51return "ok";52}53return "invalid uuid: $uuid";54}5556}57
That's it! We've just implemented two-factor authentication using three different methods and the latest in Authy technology.
If you're a PHP developer working with Twilio, you might want to check out these other tutorials.
Measure the effectiveness of different marketing campaigns with unique phone numbers.
Faster than email 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.