Register by 10/16 for $250 off the on-site price.

PHP-Laravel Quickstart for Twilio Authy Two-factor Authentication

Adding two-factor authentication to your application is the easiest way to increase security and trust in your product without unnecessarily burdening your users. This quickstart guides you through building a PHP, Laravel and AngularJS application that restricts access to a URL. Four Authy two-factor authentication channels are demoed: SMS, Voice, Soft Tokens and Push Notifications.

Ready to protect your toy app's users from nefarious balaclava wearing hackers? Dive in!

Sign Into - or Sign Up For - a Twilio Account

Create a new Twilio account (you can sign up for a free Twilio trial), or sign into an existing Twilio account.

Create a new Authy application

Once logged in, visit the Authy Console. Click on the red 'Create New Aplication' (or big red plus ('+') if you already created one) to create a new Authy application then name it something memorable.

Authy create new application

You'll automatically be transported to the Settings page next. Click the eyeball icon to reveal your Production API Key.

Account Security API Key

Copy your Production API Key to a safe place, you will use it during application setup.

Setup Authy on your device

This Authy two-factor authentication quickstart demos two channels which require an installed Authy Client to test: Soft Tokens and Push Notifications. While SMS and Voice channels will work without the client, to try out all four authentication channels download and install Authy Client for Desktop or Mobile:

Install the application prerequisites

To complete the quickstart today we'll use PHP 7.0+, Composer, MySQL, and the Twilio PHP Helper Library. Let's walk through installation below. Skip ahead if you have already installed one.

Install Composer

When doing PHP web development, we strongly suggest using Composer for package management. This quickstart relies on Composer to install the Twilio PHP Helper library. You can find manual installation instructions on the PHP Helper Library page.

Install MySQL

You'll need a database for storing Authy IDs when a user registers in this quickstart. For this demo, we built our user database on top of MySQL 5.x.

If you haven't yet installed MySQL, here are instructions for your platform:

When installed, start it. If you're using the default MySQL credentials (as below), create schema account_security with an admin user homestead and password secret.

Clone and Setup the Application

Clone our PHP repository locally, then enter the directory.

git clone git@github.com:TwilioDevEd/account-security-quickstart-php.git
cd account-security-quickstart-php
composer install

Edit the dotenv File

cp .env.example .env

Next, copy your Authy API Key from the Authy Dashboard and set the API_KEY variable in your .env file.

Loading Code Samples...
Language
# Get your API key here: https://www.twilio.com/console/authy/getting-started
API_KEY=your-authy-api-key

APP_DEBUG=true
APP_ENV=development
APP_KEY=
APP_LOG=errorlog
DB_DATABASE=account_security
DB_HOST=database
DB_PASSWORD=secret
DB_PORT=3306
DB_USERNAME=homestead
MYSQL_DATABASE=account_security
MYSQL_PASSWORD=secret
MYSQL_PORT=3306
MYSQL_ROOT_PASSWORD=secret
MYSQL_USER=homestead
SECRET=your-account-secret
Enter the API Key from the Account Security console and optionally change the port.
Add Your Application API Key

Enter the API Key from the Account Security console and optionally change the port.

 Once you have added your API Key, you are ready to run! Launch the app with:

php artisan key:generate
php artisan migrate
php artisan serve --port 8081

You should get a message your new app is running!

Try the PHP Authy Two-Factor Demo

With your phone (optionally with the Authy client installed) nearby, open a new browser tab and navigate to http://localhost:8081/register/index.html

Enter your information and invent a password, then hit 'Register'. Your information is passed to Twilio (you will be able to see your user immediately in the console), and the application is returned a user_id.

Now visit http://localhost:8081/login/index.html and login. You'll be presented with a happy screen:

Two Factor Authentication Demo

If your phone has the Authy Client installed, you can immediately enter a Soft Token from the client to Verify. Additionally, you can try a Push Notification simply by pushing the labeled button.

If you do not have the Authy Client installed, the SMS and Voice channels will also work in providing a token. To try different channels, you can logout to start the process again.

Loading Code Samples...
Language
<?php

namespace App\Http\Controllers\Auth;

use \Exception;
use App\Http\Controllers\Controller;
use App\Library\Services\OneTouch;
use App\User;
use Authy\AuthyApi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AccountSecurityController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Account Security Controller
    |--------------------------------------------------------------------------
    |
    | Uses Authy to verify a users phone via voice, sms or notifications.
    |
    */

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

    /**
     * send verification code via SMS.
     *
     * @param  Illuminate\Support\Facades\Request  $request;
     * @return Illuminate\Support\Facades\Response;
     */
    protected function sendVerificationCodeSMS(
        Request $request,
        AuthyApi $authyApi
    ) {
        $user_id = session('user_id');
        $user = User::find($user_id);
        $authyID = $user['authyID'];
        $authyApi->requestSms($authyID, ['force' => 'true']);

        return response()->json(['message' => 'Verification Code sent via SMS succesfully.']);
    }


   /**
    * send verification code via Voice Call.
    *
    * @param  Illuminate\Support\Facades\Request  $request;
    * @return Illuminate\Support\Facades\Response;
    */
    protected function sendVerificationCodeVoice(
        Request $request,
        AuthyApi $authyApi
    ) {
        $user_id = session('user_id');
        $user = User::find($user_id);
        $authyID = $user['authyID'];
        $authyApi->phoneCall($authyID, ['force' => 'true']);

        return response()->json(['message' => 'Verification Code sent via Voice Call succesfully.']);
    }

   /**
    * verify token.
    *
    * @param  Illuminate\Support\Facades\Request  $request;
    * @return Illuminate\Support\Facades\Response;
    */
    protected function verifyToken(
        Request $request,
        AuthyApi $authyApi
    ) {
        $data = $request->all();
        $token = $data['token'];
        $user_id = session('user_id');
        $user = User::find($user_id);
        $authyID = $user['authyID'];
        $authyApi->verifyToken($authyID, $token);

        return response()->json(['message' => 'Token verified successfully.']);
    }

   /**
    * Create One Touch Approval Request.
    *
    * @param  Illuminate\Support\Facades\Request  $request;
    * @return Illuminate\Support\Facades\Response;
    */
    protected function createOneTouch(
        Request $request,
        OneTouch $oneTouch
    ) {
        $data = $request->all();
        $user_id = session('user_id');
        $user = User::find($user_id);
        $authyID = $user['authyID'];
        $username =$user['username'];

        $data = [
          'message' => 'Twilio Account Security Quickstart wants authentication approval.',
          'hidden' => 'this is a hidden value',
          'visible' => [
            'username' => $username,
            'AuthyID' => $authyID,
            'Location' => 'San Francisco, CA',
            'Reason' => 'Demo by Account Security'
          ],
          'seconds_to_expire' => 120
        ];

        $onetouch_uuid = $oneTouch->createApprovalRequest($data);
        session(['onetouch_uuid' => $onetouch_uuid]);

        return response()->json(['message' => 'Token verified successfully.']);
    }

   /**
    * Get OneTouch Status.
    *
    * @param  Illuminate\Support\Facades\Request  $request;
    * @return Illuminate\Support\Facades\Response;
    */
    protected function checkOneTouchStatus(
        Request $request,
        OneTouch $oneTouch
    ) {
        $response = $oneTouch->oneTouchStatus(session('onetouch_uuid'));

        session(['authy' => $body['approval_request']['status']]);

        return response()->json($response, 200);
    }
}
Two-Factor Authentication Channels

And there you go, Authy two-factor authentication is on and your PHP/Laravel app is protected!

What's Next?

Now that you are keeping the hackers out of this demo app using Authy two-factor authentication, you can find all of the detailed descriptions for options and API calls in our Two-factor Authentication API Reference. If you're also building a registration flow, also check out our Phone Verification product and the Verify Quickstart which uses this codebase.

For additional guides and tutorials on account security and other products, in PHP and in our other languages, take a look at the Docs.

 

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

Loading Code Samples...
# Get your API key here: https://www.twilio.com/console/authy/getting-started
API_KEY=your-authy-api-key

APP_DEBUG=true
APP_ENV=development
APP_KEY=
APP_LOG=errorlog
DB_DATABASE=account_security
DB_HOST=database
DB_PASSWORD=secret
DB_PORT=3306
DB_USERNAME=homestead
MYSQL_DATABASE=account_security
MYSQL_PASSWORD=secret
MYSQL_PORT=3306
MYSQL_ROOT_PASSWORD=secret
MYSQL_USER=homestead
SECRET=your-account-secret
<?php

namespace App\Http\Controllers\Auth;

use \Exception;
use App\Http\Controllers\Controller;
use App\Library\Services\OneTouch;
use App\User;
use Authy\AuthyApi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AccountSecurityController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Account Security Controller
    |--------------------------------------------------------------------------
    |
    | Uses Authy to verify a users phone via voice, sms or notifications.
    |
    */

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

    /**
     * send verification code via SMS.
     *
     * @param  Illuminate\Support\Facades\Request  $request;
     * @return Illuminate\Support\Facades\Response;
     */
    protected function sendVerificationCodeSMS(
        Request $request,
        AuthyApi $authyApi
    ) {
        $user_id = session('user_id');
        $user = User::find($user_id);
        $authyID = $user['authyID'];
        $authyApi->requestSms($authyID, ['force' => 'true']);

        return response()->json(['message' => 'Verification Code sent via SMS succesfully.']);
    }


   /**
    * send verification code via Voice Call.
    *
    * @param  Illuminate\Support\Facades\Request  $request;
    * @return Illuminate\Support\Facades\Response;
    */
    protected function sendVerificationCodeVoice(
        Request $request,
        AuthyApi $authyApi
    ) {
        $user_id = session('user_id');
        $user = User::find($user_id);
        $authyID = $user['authyID'];
        $authyApi->phoneCall($authyID, ['force' => 'true']);

        return response()->json(['message' => 'Verification Code sent via Voice Call succesfully.']);
    }

   /**
    * verify token.
    *
    * @param  Illuminate\Support\Facades\Request  $request;
    * @return Illuminate\Support\Facades\Response;
    */
    protected function verifyToken(
        Request $request,
        AuthyApi $authyApi
    ) {
        $data = $request->all();
        $token = $data['token'];
        $user_id = session('user_id');
        $user = User::find($user_id);
        $authyID = $user['authyID'];
        $authyApi->verifyToken($authyID, $token);

        return response()->json(['message' => 'Token verified successfully.']);
    }

   /**
    * Create One Touch Approval Request.
    *
    * @param  Illuminate\Support\Facades\Request  $request;
    * @return Illuminate\Support\Facades\Response;
    */
    protected function createOneTouch(
        Request $request,
        OneTouch $oneTouch
    ) {
        $data = $request->all();
        $user_id = session('user_id');
        $user = User::find($user_id);
        $authyID = $user['authyID'];
        $username =$user['username'];

        $data = [
          'message' => 'Twilio Account Security Quickstart wants authentication approval.',
          'hidden' => 'this is a hidden value',
          'visible' => [
            'username' => $username,
            'AuthyID' => $authyID,
            'Location' => 'San Francisco, CA',
            'Reason' => 'Demo by Account Security'
          ],
          'seconds_to_expire' => 120
        ];

        $onetouch_uuid = $oneTouch->createApprovalRequest($data);
        session(['onetouch_uuid' => $onetouch_uuid]);

        return response()->json(['message' => 'Token verified successfully.']);
    }

   /**
    * Get OneTouch Status.
    *
    * @param  Illuminate\Support\Facades\Request  $request;
    * @return Illuminate\Support\Facades\Response;
    */
    protected function checkOneTouchStatus(
        Request $request,
        OneTouch $oneTouch
    ) {
        $response = $oneTouch->oneTouchStatus(session('onetouch_uuid'));

        session(['authy' => $body['approval_request']['status']]);

        return response()->json($response, 200);
    }
}