Skip to contentSkip to navigationSkip to topbar
On this page

PHP-Laravel Quickstart for Twilio Authy Two-factor Authentication


(warning)

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.

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(link takes you to an external page).

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(link takes you to an external page), Laravel(link takes you to an external page) and AngularJS(link takes you to an external page) 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

sign-into---or-sign-up-for---a-twilio-account page anchor

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

Create a new Authy application

create-a-new-authy-application page anchor

Once logged in, visit the Authy Console(link takes you to an external page). Click on the red 'Create New Application' (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

setup-authy-on-your-device page anchor

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

install-the-application-prerequisites page anchor

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.

When doing PHP web development, we strongly suggest using Composer(link takes you to an external page) 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(link takes you to an external page).

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-and-setup-the-application page anchor

Clone our PHP repository locally(link takes you to an external page), then enter the directory.

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

cp .env.example .env

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

Add Your Application API Key

add-your-application-api-key page anchor

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

1
# Get your API key here: https://www.twilio.com/console/authy/getting-started
2
API_KEY=your-authy-api-key
3
4
APP_DEBUG=true
5
APP_ENV=development
6
APP_KEY=
7
APP_LOG=errorlog
8
9
# By default, if you'd like to match this install MySQL locally.
10
# host: localhost:3306
11
# DB user: homestead
12
# DB pass: secret
13
# DB name: account_security
14
15
DB_DATABASE=account_security
16
DB_HOST=localhost
17
DB_PASSWORD=secret
18
DB_PORT=3306
19
DB_USERNAME=homestead
20
MYSQL_DATABASE=account_security
21
MYSQL_PASSWORD=secret
22
MYSQL_PORT=3306
23
MYSQL_ROOT_PASSWORD=secret
24
MYSQL_USER=homestead
25
SECRET=your-account-secret
26

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

1
php artisan key:generate
2
php artisan migrate
3
php artisan serve --port 8081

You should get a message your new app is running!


Try the PHP Authy Two-Factor Demo

try-the-php-authy-two-factor-demo page anchor

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

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(link takes you to an external page)), and the application is returned a user_id.

Now visit http://localhost:8081/login/index.html(link takes you to an external page) 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 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.

Two-Factor Authentication Channels

two-factor-authentication-channels page anchor
1
<?php
2
3
namespace App\Http\Controllers\Auth;
4
5
use \Exception;
6
use App\Http\Controllers\Controller;
7
use App\Library\Services\OneTouch;
8
use App\User;
9
use Authy\AuthyApi;
10
use Illuminate\Http\Request;
11
use Illuminate\Support\Facades\Validator;
12
13
class AccountSecurityController extends Controller
14
{
15
/*
16
|--------------------------------------------------------------------------
17
| Account Security Controller
18
|--------------------------------------------------------------------------
19
|
20
| Uses Authy to verify a users phone via voice, sms or notifications.
21
|
22
*/
23
24
/**
25
* Create a new controller instance.
26
*
27
* @return void
28
*/
29
public function __construct()
30
{
31
$this->middleware('auth');
32
}
33
34
/**
35
* send verification code via SMS.
36
*
37
* @param Illuminate\Support\Facades\Request $request;
38
* @return Illuminate\Support\Facades\Response;
39
*/
40
protected function sendVerificationCodeSMS(
41
Request $request,
42
AuthyApi $authyApi
43
) {
44
$user_id = session('user_id');
45
$user = User::find($user_id);
46
$authyID = $user['authyID'];
47
$authyApi->requestSms($authyID, ['force' => 'true']);
48
49
return response()->json(['message' => 'Verification Code sent via SMS succesfully.']);
50
}
51
52
53
/**
54
* send verification code via Voice Call.
55
*
56
* @param Illuminate\Support\Facades\Request $request;
57
* @return Illuminate\Support\Facades\Response;
58
*/
59
protected function sendVerificationCodeVoice(
60
Request $request,
61
AuthyApi $authyApi
62
) {
63
$user_id = session('user_id');
64
$user = User::find($user_id);
65
$authyID = $user['authyID'];
66
$authyApi->phoneCall($authyID, ['force' => 'true']);
67
68
return response()->json(['message' => 'Verification Code sent via Voice Call succesfully.']);
69
}
70
71
/**
72
* verify token.
73
*
74
* @param Illuminate\Support\Facades\Request $request;
75
* @return Illuminate\Support\Facades\Response;
76
*/
77
protected function verifyToken(
78
Request $request,
79
AuthyApi $authyApi
80
) {
81
$data = $request->all();
82
$token = $data['token'];
83
$user_id = session('user_id');
84
$user = User::find($user_id);
85
$authyID = $user['authyID'];
86
$authyApi->verifyToken($authyID, $token);
87
88
return response()->json(['message' => 'Token verified successfully.']);
89
}
90
91
/**
92
* Create One Touch Approval Request.
93
*
94
* @param Illuminate\Support\Facades\Request $request;
95
* @return Illuminate\Support\Facades\Response;
96
*/
97
protected function createOneTouch(
98
Request $request,
99
OneTouch $oneTouch
100
) {
101
$data = $request->all();
102
$user_id = session('user_id');
103
$user = User::find($user_id);
104
$authyID = $user['authyID'];
105
$username =$user['username'];
106
107
$data = [
108
'message' => 'Twilio Account Security Quickstart wants authentication approval.',
109
'hidden' => 'this is a hidden value',
110
'visible' => [
111
'username' => $username,
112
'AuthyID' => $authyID,
113
'Location' => 'San Francisco, CA',
114
'Reason' => 'Demo by Account Security'
115
],
116
'seconds_to_expire' => 120
117
];
118
119
$onetouch_uuid = $oneTouch->createApprovalRequest($data);
120
session(['onetouch_uuid' => $onetouch_uuid]);
121
122
return response()->json(['message' => 'Token verified successfully.']);
123
}
124
125
/**
126
* Get OneTouch Status.
127
*
128
* @param Illuminate\Support\Facades\Request $request;
129
* @return Illuminate\Support\Facades\Response;
130
*/
131
protected function checkOneTouchStatus(
132
Request $request,
133
OneTouch $oneTouch
134
) {
135
$response = $oneTouch->oneTouchStatus(session('onetouch_uuid'));
136
137
session(['authy' => $body['approval_request']['status']]);
138
139
return response()->json($response, 200);
140
}
141
}
142

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


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?

Terms of service

Copyright © 2024 Twilio Inc.