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
_10APP_ENV=local_10APP_DEBUG=true_10APP_KEY=ufxhZiQcKxi1eHVmGq8MwfAcRgZHJ1Qq_10_10DB_HOST=localhost_10DB_DATABASE=authy_laravel_10DB_USERNAME=your_db_username_10DB_PASSWORD=your_db_password_10_10AUTHY_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
_63<?php namespace App;_63_63use Illuminate\Auth\Authenticatable;_63use Illuminate\Database\Eloquent\Model;_63use Illuminate\Auth\Passwords\CanResetPassword;_63use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;_63use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;_63_63class User extends Model implements AuthenticatableContract, CanResetPasswordContract_63{_63_63 use Authenticatable, CanResetPassword;_63_63 /**_63 * The database table used by the model._63 *_63 * @var string_63 */_63 protected $table = 'users';_63_63 /**_63 * The attributes that are mass assignable._63 *_63 * @var array_63 */_63 protected $fillable = ['name', 'email', 'password', 'phone_number', 'country_code'];_63_63 /**_63 * The attributes excluded from the model's JSON form._63 *_63 * @var array_63 */_63 protected $hidden = ['password', 'remember_token', 'authy_status', 'authy_id'];_63_63_63 /**_63 * @param $authy_id string_63 */_63 public function updateAuthyId($authy_id) {_63 if($this->authy_id != $authy_id) {_63 $this->authy_id = $authy_id;_63 $this->save();_63 }_63 }_63_63 /**_63 * @param $status string_63 */_63 public function updateVerificationStatus($status) {_63 // reset oneTouch status_63 if ($this->authy_status != $status) {_63 $this->authy_status = $status;_63 $this->save();_63 }_63 }_63_63 public function updateOneTouchUuid($uuid) {_63 if ($this->authy_one_touch_uuid != $uuid) {_63 $this->authy_one_touch_uuid = $uuid;_63 $this->save();_63 }_63 }_63}
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:
app/Http/Controllers/Auth/AuthController.php
_126<?php namespace App\Http\Controllers\Auth;_126_126use App\Authy\Service;_126use App\OneTouch;_126use Auth;_126use Session;_126use App\User;_126use App\Http\Controllers\Controller;_126use Illuminate\Http\Request;_126use Illuminate\Contracts\Auth\Guard;_126use Illuminate\Contracts\Auth\Registrar;_126use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;_126use function Stringy\create;_126_126_126class AuthController extends Controller_126{_126_126 /*_126 |--------------------------------------------------------------------------_126 | Registration & Login Controller_126 |--------------------------------------------------------------------------_126 |_126 | This controller handles the registration of new users, as well as the_126 | authentication of existing users. By default, this controller uses_126 | a simple trait to add these behaviors. Why don't you explore it?_126 |_126 */_126_126 use AuthenticatesAndRegistersUsers;_126_126 /**_126 * Create a new authentication controller instance._126 *_126 * @param \Illuminate\Contracts\Auth\Guard $auth_126 * @param \Illuminate\Contracts\Auth\Registrar $registrar_126 * @param \App\Authy\Service $authy_126 */_126 public function __construct(Guard $auth, Registrar $registrar, Service $authy)_126 {_126 $this->auth = $auth;_126 $this->registrar = $registrar;_126 $this->authy = $authy;_126_126 $this->middleware('guest', ['except' => 'getLogout']);_126 }_126_126 public function postLogin(Request $request)_126 {_126 $credentials = $request->only('email', 'password');_126 if (Auth::validate($credentials)) {_126 $user = User::where('email', '=', $request->input('email'))->firstOrFail();_126_126 Session::set('password_validated', true);_126 Session::set('id', $user->id);_126_126 if ($this->authy->verifyUserStatus($user->authy_id)->registered) {_126 $uuid = $this->authy->sendOneTouch($user->authy_id, 'Request to Login to Twilio demo app');_126_126 OneTouch::create(['uuid' => $uuid]);_126_126 Session::set('one_touch_uuid', $uuid);_126_126 return response()->json(['status' => 'ok']);_126 } else_126 return response()->json(['status' => 'verify']);_126_126 } else {_126 return response()->json(['status' => 'failed',_126 'message' => 'The email and password combination you entered is incorrect.']);_126 }_126 }_126_126 public function getTwoFactor()_126 {_126 $message = Session::get('message');_126_126 return view('auth/two-factor', ['message' => $message]);_126 }_126_126 public function postTwoFactor(Request $request)_126 {_126 if (!Session::get('password_validated') || !Session::get('id')) {_126 return redirect('/auth/login');_126 }_126_126 if (isset($_POST['token'])) {_126 $user = User::find(Session::get('id'));_126 if ($this->authy->verifyToken($user->authy_id, $request->input('token'))) {_126 Auth::login($user);_126 return redirect()->intended('/home');_126 } else {_126 return redirect('/auth/two-factor')->withErrors([_126 'token' => 'The token you entered is incorrect',_126 ]);_126 }_126 }_126 }_126_126 public function postRegister(Request $request)_126 {_126 $validator = $this->registrar->validator($request->all());_126 if ($validator->fails()) {_126 $this->throwValidationException(_126 $request, $validator_126 );_126 }_126 $user = $this->registrar->create($request->all());_126_126 Session::set('password_validated', true);_126 Session::set('id', $user->id);_126_126 $authy_id = $this->authy->register($user->email, $user->phone_number, $user->country_code);_126_126 $user->updateAuthyId($authy_id);_126_126 if ($this->authy->verifyUserStatus($authy_id)->registered)_126 $message = "Open Authy app in your phone to see the verification code";_126 else {_126 $this->authy->sendToken($authy_id);_126 $message = "You will receive an SMS with the verification code";_126 }_126_126 return redirect('/auth/two-factor')->with('message', $message);_126 }_126}
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 easily 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.
_10$params = array(_10 'message' => "Request to send money to Jarod's vault",_10 'details[From]' => "Jarod",_10 'details[Amount]' => "1,000,000",_10 'details[Currency]' => "Galleons",_10)
Once we send the request we need to update our User's authy_status
based on the response.
app/User.php
_63<?php namespace App;_63_63use Illuminate\Auth\Authenticatable;_63use Illuminate\Database\Eloquent\Model;_63use Illuminate\Auth\Passwords\CanResetPassword;_63use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;_63use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;_63_63class User extends Model implements AuthenticatableContract, CanResetPasswordContract_63{_63_63 use Authenticatable, CanResetPassword;_63_63 /**_63 * The database table used by the model._63 *_63 * @var string_63 */_63 protected $table = 'users';_63_63 /**_63 * The attributes that are mass assignable._63 *_63 * @var array_63 */_63 protected $fillable = ['name', 'email', 'password', 'phone_number', 'country_code'];_63_63 /**_63 * The attributes excluded from the model's JSON form._63 *_63 * @var array_63 */_63 protected $hidden = ['password', 'remember_token', 'authy_status', 'authy_id'];_63_63_63 /**_63 * @param $authy_id string_63 */_63 public function updateAuthyId($authy_id) {_63 if($this->authy_id != $authy_id) {_63 $this->authy_id = $authy_id;_63 $this->save();_63 }_63 }_63_63 /**_63 * @param $status string_63 */_63 public function updateVerificationStatus($status) {_63 // reset oneTouch status_63 if ($this->authy_status != $status) {_63 $this->authy_status = $status;_63 $this->save();_63 }_63 }_63_63 public function updateOneTouchUuid($uuid) {_63 if ($this->authy_one_touch_uuid != $uuid) {_63 $this->authy_one_touch_uuid = $uuid;_63 $this->save();_63 }_63 }_63}
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 keep it simple and just update the authy_status
on the User.
app/Http/Controllers/Auth/AuthyController.php
_56<?php namespace App\Http\Controllers\Auth;_56_56use App\OneTouch;_56use Auth;_56use Session;_56use App\User;_56use App\Http\Controllers\Controller;_56use Illuminate\Http\Request;_56_56class AuthyController extends Controller_56{_56 /**_56 * Create a new controller instance._56 *_56 * @return void_56 */_56 public function __construct()_56 {_56 $this->middleware('guest');_56 }_56_56 /**_56 * Check One Touch authorization status_56 *_56 * @param Request $request_56 * @return \Illuminate\Http\JsonResponse_56 */_56 public function status(Request $request)_56 {_56 $oneTouch = OneTouch::where('uuid', '=', Session::get('one_touch_uuid'))->firstOrFail();_56 $status = $oneTouch->status;_56 if ($status == 'approved') {_56 Auth::login(User::find(Session::get('id')));_56 }_56 return response()->json(['status' => $status]);_56 }_56_56 /**_56 * Public webhook for Authy_56 *_56 * @param Request $request_56 * @return string_56 */_56 public function callback(Request $request)_56 {_56 $uuid = $request->input('uuid');_56 $oneTouch = OneTouch::where('uuid', '=', $uuid)->first();_56 if ($oneTouch != null) {_56 $oneTouch->status = $request->input('status');_56 $oneTouch->save();_56 return "ok";_56 }_56 return "invalid uuid: $uuid";_56 }_56_56}
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
_48$(document).ready(function() {_48 console.log('loaded');_48 $('#login-form').submit(function(e) {_48 e.preventDefault();_48 formData = $(e.currentTarget).serialize();_48 attemptOneTouchVerification(formData);_48 });_48_48 var attemptOneTouchVerification = function(form) {_48 $('#ajax-error').addClass('hidden');_48 $.post( "/auth/login", form, function(data) {_48 if (data.status === 'ok') {_48 $('#authy-modal').modal({backdrop:'static'},'show');_48 $('.auth-ot').fadeIn();_48 checkForOneTouch();_48 } else if (data.status === 'verify') {_48 $('#authy-modal').modal({backdrop:'static'},'show');_48 $('.auth-token').fadeIn()_48 } else if (data.status === 'failed') {_48 $('#ajax-error').html(data.message);_48 $('#ajax-error').removeClass('hidden');_48 }_48 });_48 };_48_48 var checkForOneTouch = function() {_48 $.get("/authy/status", function (data) {_48 if (data.status === 'approved') {_48 window.location.href = "/home";_48 } else if (data.status === 'denied') {_48 showTokenForm();_48 triggerSMSToken();_48 } else {_48 setTimeout(checkForOneTouch, 5000);_48 }_48 });_48 };_48_48 var showTokenForm = function() {_48 $('.auth-ot').fadeOut(function() {_48 $('.auth-token').fadeIn('slow')_48 })_48 };_48_48 var triggerSMSToken = function() {_48 $.get("/authy/send_token")_48 };_48});
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
_56<?php namespace App\Http\Controllers\Auth;_56_56use App\OneTouch;_56use Auth;_56use Session;_56use App\User;_56use App\Http\Controllers\Controller;_56use Illuminate\Http\Request;_56_56class AuthyController extends Controller_56{_56 /**_56 * Create a new controller instance._56 *_56 * @return void_56 */_56 public function __construct()_56 {_56 $this->middleware('guest');_56 }_56_56 /**_56 * Check One Touch authorization status_56 *_56 * @param Request $request_56 * @return \Illuminate\Http\JsonResponse_56 */_56 public function status(Request $request)_56 {_56 $oneTouch = OneTouch::where('uuid', '=', Session::get('one_touch_uuid'))->firstOrFail();_56 $status = $oneTouch->status;_56 if ($status == 'approved') {_56 Auth::login(User::find(Session::get('id')));_56 }_56 return response()->json(['status' => $status]);_56 }_56_56 /**_56 * Public webhook for Authy_56 *_56 * @param Request $request_56 * @return string_56 */_56 public function callback(Request $request)_56 {_56 $uuid = $request->input('uuid');_56 $oneTouch = OneTouch::where('uuid', '=', $uuid)->first();_56 if ($oneTouch != null) {_56 $oneTouch->status = $request->input('status');_56 $oneTouch->save();_56 return "ok";_56 }_56 return "invalid uuid: $uuid";_56 }_56_56}
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.
Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Connect with us on Twitter and let us know what you build!