How to Secure Laravel Apps with 2FA via SMS

This article was peer reviewed by Christopher Thomas. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

While everyone is concerned about their application’s security, few take it seriously and take the plunge. The first thing you’ll notice when learning about this is that two factor authentication (2FA) is the go-to solution as a first step.

Although there have been some serious problems with using text messages as a second factor, it’s definitely safer than a plain username and password combination, given that many users tend to use popular and easy to guess passwords for critical services such as payments, chat, emails, etc. In this article, we’re going to build two factor authentication into a Laravel application using Twilio SMS as the second factor.

What We’re Building

There’s a great chance that you’re already familiar with the 2FA flow:

User visits the login page.

He types in an email and a password.

We send a verification code using the phone number.

User must type in the received code.

If the code is correct, we log them in. Otherwise, we give them another chance to try logging in.

Every user has a list of tokens (verification codes) that they generated. Run the php artisan make:model Token -m command to generate the model and migration file. The table schema will look like this:

After validating the request, we try to retrieve a user using the email and password. If the user exists, we create a new token for this user, then we send the code, set the necessary session details, and redirect to the code page.

Ooh wait! We didn’t define a sendCode method inside the Token model?

Adding Twilio

Before sending the code to the user via SMS, we need to configure Twilio for the job. We need to create a new trial account.

Conclusion

This article was a quick introduction to integrating two factor authentication with Twilio with a Laravel application. You can also take this demo further by giving the users the ability to enable and disable two factor authentication, and you may also want to offer a call instead of an SMS!

Have you ever implemented 2FA for an application? What are the challenges you’ve faced? Was it a good experience for your users?

If you have any question or comments about 2FA or Laravel, you can post them below!

Younes is a freelance web developer, technical writer and a blogger from Morocco. He's worked with JAVA, J2EE, JavaScript, etc., but his language of choice is PHP. You can learn more about him on his website.