# Two-Factor Authentication with Authy, PHP and Laravel

> \[!WARNING]
>
> 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](/docs/verify/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](https://www.twilio.com/blog/migrate-authy-to-verify).

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](/docs/glossary/what-is-two-factor-authentication-2fa) determines the identity of a user by validating once by logging into the app, and then by validating their mobile device.

This [PHP](https://www.php.net/) [Laravel](https://laravel.com/) 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](https://github.com/TwilioDevEd/authy2fa-laravel).

For the second factor, we will validate that the user has their mobile phone by either:

* Sending them a OneTouch push notification to their mobile Authy Client app or
* Sending them a token through their mobile Authy app or
* Sending them a one-time token in a text message.

*[See how VMware uses Twilio Two-Factor Authentication to secure their enterprise mobility management solution.](https://customers.twilio.com/1143/vmware/?utm_source=docs\&utm_campaign=docs_to_stories)*

## Configuring Authy

If you haven't configured Authy already, now is the time to [sign up for Authy](https://dashboard.authy.com/signup). Create your first application naming it as you wish. After you create your application, your "production" API key will be visible on your [dashboard](https://dashboard.authy.com)

Once we have an Authy API key we can register it as an environment variable.

```bash title="Configure Authy environment variables" description=".env.example"
# !mark(10)
APP_ENV=local
APP_DEBUG=true
APP_KEY=ufxhZiQcKxi1eHVmGq8MwfAcRgZHJ1Qq

DB_HOST=localhost
DB_DATABASE=authy_laravel
DB_USERNAME=your_db_username
DB_PASSWORD=your_db_password

AUTHY_API_KEY=your_token
```

Let's take a look at how we register a user with Authy.

## 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.

```php title="Register a User with Authy" description="app/User.php"
// !mark(35,36,37,38,39,40,41,42,43,44,45,46,47)
<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{

    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'phone_number', 'country_code'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token', 'authy_status', 'authy_id'];


    /**
     * @param $authy_id string
     */
    public function updateAuthyId($authy_id) {
        if($this->authy_id != $authy_id) {
            $this->authy_id = $authy_id;
            $this->save();
        }
    }

    /**
     * @param $status string
     */
    public function updateVerificationStatus($status) {
        // reset oneTouch status
        if ($this->authy_status != $status) {
            $this->authy_status = $status;
            $this->save();
        }
    }

    public function updateOneTouchUuid($uuid) {
        if ($this->authy_one_touch_uuid != $uuid) {
            $this->authy_one_touch_uuid = $uuid;
            $this->save();
        }
    }
}

```

## Log in with Authy OneTouch

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:

* We attempt to send a User a *[OneTouch Approval Request](/docs/authy/api)*.
* If the User has OneTouch enabled we will get a *success* message back.
* The User hits **Approve** in their Authy app.
* Authy makes a `POST` request to our app with an *approved* status.
* We log the User in.

```php title="Log in with Authy OneTouch" description="app/Http/Controllers/Auth/AuthController.php"
// !mark(43:56)
<?php namespace App\Http\Controllers\Auth;

use App\Authy\Service;
use App\OneTouch;
use Auth;
use Session;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use function Stringy\create;


class AuthController extends Controller
{

    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers;

    /**
     * Create a new authentication controller instance.
     *
     * @param  \Illuminate\Contracts\Auth\Guard $auth
     * @param  \Illuminate\Contracts\Auth\Registrar $registrar
     * @param  \App\Authy\Service $authy
     */
    public function __construct(Guard $auth, Registrar $registrar, Service $authy)
    {
        $this->auth = $auth;
        $this->registrar = $registrar;
        $this->authy = $authy;

        $this->middleware('guest', ['except' => 'getLogout']);
    }

    public function postLogin(Request $request)
    {
        $credentials = $request->only('email', 'password');
        if (Auth::validate($credentials)) {
            $user = User::where('email', '=', $request->input('email'))->firstOrFail();

            Session::set('password_validated', true);
            Session::set('id', $user->id);

            if ($this->authy->verifyUserStatus($user->authy_id)->registered) {
                $uuid = $this->authy->sendOneTouch($user->authy_id, 'Request to Login to Twilio demo app');

                OneTouch::create(['uuid' => $uuid]);

                Session::set('one_touch_uuid', $uuid);

                return response()->json(['status' => 'ok']);
            } else
                return response()->json(['status' => 'verify']);

        } else {
            return response()->json(['status' => 'failed',
                'message' => 'The email and password combination you entered is incorrect.']);
        }
    }

    public function getTwoFactor()
    {
        $message = Session::get('message');

        return view('auth/two-factor', ['message' => $message]);
    }

    public function postTwoFactor(Request $request)
    {
        if (!Session::get('password_validated') || !Session::get('id')) {
            return redirect('/auth/login');
        }

        if (isset($_POST['token'])) {
            $user = User::find(Session::get('id'));
            if ($this->authy->verifyToken($user->authy_id, $request->input('token'))) {
                Auth::login($user);
                return redirect()->intended('/home');
            } else {
                return redirect('/auth/two-factor')->withErrors([
                    'token' => 'The token you entered is incorrect',
                ]);
            }
        }
    }

    public function postRegister(Request $request)
    {
        $validator = $this->registrar->validator($request->all());
        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }
        $user = $this->registrar->create($request->all());

        Session::set('password_validated', true);
        Session::set('id', $user->id);

        $authy_id = $this->authy->register($user->email, $user->phone_number, $user->country_code);

        $user->updateAuthyId($authy_id);

        if ($this->authy->verifyUserStatus($authy_id)->registered)
            $message = "Open Authy app in your phone to see the verification code";
        else {
            $this->authy->sendToken($authy_id);
            $message = "You will receive an SMS with the verification code";
        }

        return redirect('/auth/two-factor')->with('message', $message);
    }
}

```

## Send the OneTouch 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 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.

```bash
$params = array(
  'message' => "Request to send money to Jarod's vault",
  'details[From]' => "Jarod",
  'details[Amount]' => "1,000,000",
  'details[Currency]' => "Galleons",
)

```

Once we send the request we need to update our User's `authy_status` based on the response.

```php title="Send the OneTouch Request" description="app/User.php"
// !mark(49:63)
<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{

    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'phone_number', 'country_code'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token', 'authy_status', 'authy_id'];


    /**
     * @param $authy_id string
     */
    public function updateAuthyId($authy_id) {
        if($this->authy_id != $authy_id) {
            $this->authy_id = $authy_id;
            $this->save();
        }
    }

    /**
     * @param $status string
     */
    public function updateVerificationStatus($status) {
        // reset oneTouch status
        if ($this->authy_status != $status) {
            $this->authy_status = $status;
            $this->save();
        }
    }

    public function updateOneTouchUuid($uuid) {
        if ($this->authy_one_touch_uuid != $uuid) {
            $this->authy_one_touch_uuid = $uuid;
            $this->save();
        }
    }
}

```

## Configure the OneTouch callback

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.

```php title="Update user status using Authy Callback" description="app/Http/Controllers/Auth/AuthyController.php"
// !mark(33,34,35,36,37,38,39,40,41,42,43,44)
<?php namespace App\Http\Controllers\Auth;

use App\OneTouch;
use Auth;
use Session;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthyController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Check One Touch authorization status
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function status(Request $request)
    {
        $oneTouch = OneTouch::where('uuid', '=', Session::get('one_touch_uuid'))->firstOrFail();
        $status = $oneTouch->status;
        if ($status == 'approved') {
            Auth::login(User::find(Session::get('id')));
        }
        return response()->json(['status' => $status]);
    }

    /**
     * Public webhook for Authy
     *
     * @param Request $request
     * @return string
     */
    public function callback(Request $request)
    {
        $uuid = $request->input('uuid');
        $oneTouch = OneTouch::where('uuid', '=', $uuid)->first();
        if ($oneTouch != null) {
            $oneTouch->status = $request->input('status');
            $oneTouch->save();
            return "ok";
        }
        return "invalid uuid: $uuid";
    }

}

```

Let's take a look at the client-side code that will be handling this.

## Disabling Unsuccessful Callbacks

**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

* Set the OneTouch callback URL to blank.
* Send an email notifying you that the OneTouch callback is disabled with details on how to enable the OneTouch callback.

**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.

## Handle Two-Factor in the Browser

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.

```js title="Handle Two-Factor in the Browser" description="public/js/sessions.js"
$(document).ready(function() {
  console.log('loaded');
  $('#login-form').submit(function(e) {
    e.preventDefault();
    formData = $(e.currentTarget).serialize();
    attemptOneTouchVerification(formData);
  });

  var attemptOneTouchVerification = function(form) {
      $('#ajax-error').addClass('hidden');
      $.post( "/auth/login", form, function(data) {
      if (data.status === 'ok') {
        $('#authy-modal').modal({backdrop:'static'},'show');
        $('.auth-ot').fadeIn();
        checkForOneTouch();
      } else if (data.status === 'verify') {
        $('#authy-modal').modal({backdrop:'static'},'show');
        $('.auth-token').fadeIn()
      } else if (data.status === 'failed') {
        $('#ajax-error').html(data.message);
        $('#ajax-error').removeClass('hidden');
      }
    });
  };

  var checkForOneTouch = function() {
    $.get("/authy/status", function (data) {
      if (data.status === 'approved') {
        window.location.href = "/home";
      } else if (data.status === 'denied') {
        showTokenForm();
        triggerSMSToken();
      } else {
        setTimeout(checkForOneTouch, 5000);
      }
    });
  };

  var showTokenForm = function() {
    $('.auth-ot').fadeOut(function() {
      $('.auth-token').fadeIn('slow')
    })
  };

  var triggerSMSToken = function() {
    $.get("/authy/send_token")
  };
});

```

## Finishing the 2FA Step

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*.

```php title="Redirect user to the correct page based on authentication status" description="app/Http/Controllers/Auth/AuthyController.php"
// !mark(23,24,25,26,27,28,29,30,31)
<?php namespace App\Http\Controllers\Auth;

use App\OneTouch;
use Auth;
use Session;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthyController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Check One Touch authorization status
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function status(Request $request)
    {
        $oneTouch = OneTouch::where('uuid', '=', Session::get('one_touch_uuid'))->firstOrFail();
        $status = $oneTouch->status;
        if ($status == 'approved') {
            Auth::login(User::find(Session::get('id')));
        }
        return response()->json(['status' => $status]);
    }

    /**
     * Public webhook for Authy
     *
     * @param Request $request
     * @return string
     */
    public function callback(Request $request)
    {
        $uuid = $request->input('uuid');
        $oneTouch = OneTouch::where('uuid', '=', $uuid)->first();
        if ($oneTouch != null) {
            $oneTouch->status = $request->input('status');
            $oneTouch->save();
            return "ok";
        }
        return "invalid uuid: $uuid";
    }

}

```

That's it! We've just implemented two-factor authentication using three different methods and the latest in Authy technology.

## Where to next?

If you're a PHP developer working with Twilio, you might want to check out these other tutorials.

**[Call Tracking](/blog/call-tracking-php-laravel)**

Measure the effectiveness of different marketing campaigns with unique phone numbers.

**[Server Notifications via SMS](/blog/server-notifications-php)**

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.
