Secure Your Laravel Apps with Two-Factor Authentication and Laravel Fortify
Time to read:
Secure Your Laravel Apps with Two-Factor Authentication and Laravel Fortify
Security has always been a major challenge in web applications, especially with user authentication. With the increasing number of cyber threats, relying solely on passwords is no longer enough. Attackers can easily compromise weak or reused passwords through phishing, brute force attacks, or data breaches. To enhance security, Two-Factor Authentication (2FA) has become a widely adopted solution.
Laravel Fortify, Laravel’s authentication backend, provides built-in support for two-factor authentication using TOTP (Time-based One-Time Passwords). However, many users find SMS-based authentication more convenient than using authentication apps. That’s where Twilio comes in. Twilio’s SMS API allows us to send OTPs directly to users’ mobile devices, making the authentication process more seamless and user-friendly.
In this tutorial, you will learn how to secure your Laravel apps by implementing SMS-based 2FA using Twilio and Laravel Fortify.
What is Two-factor authentication?
Two-factor authentication (2FA), sometimes called Two-step Verification or Dual-factor Authentication, is a security process in which users provide two different authentication factors to verify themselves.
2FA adds an extra layer of protection to Laravel applications by requiring users to verify their identity through a second authentication factor, typically an OTP (One-Time Password) sent via SMS, email, or an authentication app. With using it, even if an attacker gains access to a user’s password, they still cannot log in without the second verification step.
What is Laravel Fortify?
Laravel Fortify is a frontend agnostic authentication backend implementation for Laravel. This means that Laravel Fortify provides all the necessary backend logic for user registration, login, password resets, email verification, and other authentication features without dictating how the user interface should look. With this flexibility, you can design and implement a fully customized frontend while smoothly leveraging Fortify’s powerful authentication features in the background.
Prerequisites
- Composer installed globally
- PHP 8.3 or higher
- A free or paid Twilio account. Create a free account if you are new to Twilio
- A phone to receive SMS
- Your preferred text editor or IDE
Scaffold a basic Laravel project
Given that Composer is installed globally on your computer, start a new project by running the following command, wherever you store your PHP projects:
To proceed with the installation process, choose "No starter kit"and "Pest" as your desired testing framework when prompted.


Still at the installation stage. In the next step, select "SQLite" as the database for your application, then confirm "Yes" to run the default database migrations.


After completing the installation process, your project should be successfully created. Navigate into its directory by running the following command:
Next, start the development server by running the following command:
Now, you can access your newly created application in your browser by visiting: http://localhost:8000. You should see the default Laravel welcome page confirming your application is running successfully.


Install and configure Laravel Fortify
To install Laravel Fortify, run the following command in a new terminal window or tab:
To publish Fortify's authentication actions to the app/Actions directory, generate the FortifyServiceProvider, publish the Fortify configuration file, and include all necessary database migrations required for authentication, run the following command:
Next, open the project directory in your IDE or editor of choice. Then, navigate to app/Actions/Fortify directory, open the CreateNewUser.php file, and update with the following code.
This code manages the user registration using Laravel Fortify. The key update made was including a phone number field because you will be receiving the authentication code via SMS.
Update the users table
The "users" table is an important database table in this tutorial. It stores and manages user-related information. It acts as the foundation for user data management, authorization, and authentication.
Now, let's update the user migration file. Navigate to database/migrations directory, open the last file whose name ends with _add_two_factor_columns_to_users_table.php, and update the table with the code below:
Laravel Fortify automatically implements the "name", "email", and "password" fields. In addition, the following fields were added to the table:
- phone: This stores the user's phone number, which is required for sending SMS-based OTPs
- two_factor_code: This stores the OTP (One-Time Password) generated for 2FA
- two_factor_expires_at: This stores the expiration time for the OTP, ensuring that the OTP is valid only for a limited period
Next, run the following command to migrate your database:
Update the User model
The User
model serves as the primary representation of the users
table. It interacts with the "users" table in the database and provides authentication, enabling data retrieval and notification handling. To update the User
model, navigate to the app/Models directory, open the User.php file, and update it with the code below:
The $fillable
array defines which attributes can be mass assigned when creating or updating a user, and the $hidden
array defines which attributes should not be included in JSON responses.
Install Twilio's Official PHP Helper Library
To simplify interacting with Twilio's Programmable Messaging API, you will need Twilio's PHP Helper Library installed. To install the library, run the command below.
Retrieve your Twilio credentials
Before proceeding, it's important to securely store your credentials to prevent exposing sensitive information in your codebase. Instead of hardcoding credentials, you can dynamically retrieve them from environment variables stored in the .env file.
To properly use these credentials, navigate to the config directory, open the services.php file, and add the following configuration code:
Now, copy and paste the following at the end of .env, located in the project's top-level directory.
Next, you need to retrieve these three key credentials from your Twilio account:
- Account SID: A unique identifier for your Twilio account
- Auth Token: A secret key used for authentication
- Twilio Phone Number: A virtual number assigned to your account for sending messages and making calls


Now, log in to your Twilio Dashboard and copy these credentials located in the Account Info section, into .env, replacing the respective placeholders.
Create a Twilio service
Now, let's create the 2FA service to handle SMS operations. Navigate to your app directory and create a new folder named Services. Inside the Services folder, create a new file named TwilioService.php, and add the following code to the file:
This service class initializes Twilio's REST API client using the credentials stored in config/services.php, and provides a reusable method to send SMS messages.
Create the controller
Now, let's generate a controller named TwoFactorController. To do this, run the following command:
Next, navigate to your app/Http/Controllers directory, open TwoFactorController.php file, and replace its content with the following code:
This controller handles the generation, storage, and verification of the 2FA code. It also ensures that users cannot log in without verifying their identity through the Twilio SMS-based authentication code.
Let’s go step-by-step and analyze how these methods are implemented:
- The
verifyPage()
method prevents unauthorized access - The
sendCode()
method generates a random 6-digit code, saves it to the database, and sends it to the user via SMS - The
verifyCode()
method validates the entered code and grants access if it is correct - The
authenticated()
method ensures that users verify their 2FA code before moving to the next page
Create the frontend view
Now, let's implement the application's frontend view by creating the template files for the authentication controller’s methods. To create the frontend template files, navigate to the resources/views directory and create a new folder named auth. Inside the auth folder, create the following files:
- register.blade.php
- login.blade.php
- two-factor.blade.php
Now, inside the register.blade.php file, add the code below.
Inside the login.blade.php file, add the code below.
Inside the two-factor.blade.php file, add the code below.
Now, navigate to the resources/views directory and create a new folder named layouts. Inside this folder, create a file called app.blade.php. This file will serve as the main layout for your application, providing a consistent structure for all your pages. Add the following code to this file.
Lastly, create the home page ( home.blade.php) inside the resource/views directory. Add the following code:
Add the routes
Let's define how the application will handle incoming requests by integrating the web routes. Navigate to the routes directory, open the web.php file, and update it to match the following code:
Now, let's configure the redirection path for authenticated users. By default, Laravel Fortify automatically handles this, but you need to customize it to ensure users are directed to the two-factor authentication page.
To do this, navigate to the config directory, open the fortify.php file, and update the home
path from /home
to /2fa
.
Customize the Fortify Service Provider
TheFortify Service Provideris a backend authentication implementation for Laravel applications. This Service Provider customizes authentication behavior, defines views, and enforces the 2FA.
To customize the Fortify Service Provider, navigate to the app/Providers directory, open the FortifyServiceProvider.php file, and replace its contents with the following code:
The customizations made to this code are as follows:
- Authentication using phone instead of email: The authentication system has been modified to use a phone number and password instead of the default email and password combination
- Custom authentication views: Instead of using Fortify's default views, custom authentication views have been set, allowing for a fully tailored user interface
- 2FA enforcement: If a user has 2FA enabled, they are redirected to a verification page before completing the login process
- Rate limiting for login and 2FA: To enhance security, rate limits have been implemented for both login attempts and two-factor authentication, preventing excessive or automated login attempts
Test the application
To test the application, open http://127.0.0.1:8000/register in your browser and complete the registration form as shown in the screenshot below.


Once registered, you will be redirected to the 2FA page. As shown in the screenshot, click the Send Code button to receive an SMS from Twilio containing your 2FA code.


Enter the received code, click the Verify button, and upon successful verification, you will be redirected to the home page.
If you're already a registered user, visit http://127.0.0.1:8000/login and log in using your email and password, as shown in the screenshot below.


That's how to Implement 2FA with Twilio and Laravel Fortify
Integrating Twilio for SMS-based authentication enables users to receive a unique verification code that must be entered to complete the registration and login process. Laravel Fortify simplifies this implementation by handling the authentication logic, while Twilio ensures reliable message delivery — as always.
With this setup, you can secure your Laravel apps from unauthorized access, improving security and trust. For even greater flexibility and security, you can extend this implementation by incorporating other authentication methods, such as email-based verification or app-based authenticators.
Happy coding!
Lucky Opuama is a software engineer and technical writer with a passion for exploring new tech stacks and writing about them. Connect with him on LinkedIn.
Password icon created by kliwir art on Flaticon.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.