This tutorial is out of date and no longer maintained.
Laravel is a wonderful PHP framework that makes building applications with PHP a lot of fun.
One of the nice features of Laravel is how easy it is to set up user authentication. It includes everything from registering to authentication and even password retrieval.
However, with the state of things at the moment, the regular email and password login method is becoming less and less secure. Brute force attacks, phishing scams, data breaches, and SQL injection attacks have become so common that usernames and passwords can be easily cracked, captured, and leaked. Also, the use of weak passwords, the same passwords across multiple accounts, and insecure wifi networks, put many people in jeopardy of getting hacked.
Two-factor authentication (2FA) strengthens access security by requiring two methods (also referred to as factors) to verify your identity. Two-factor authentication protects against phishing, social engineering, and password brute force attacks and secures your logins from attackers exploiting weak or stolen credentials.
In this tutorial, we are going to learn how to add two-factor authentication to our Laravel application. We’ll be using Google Authenticator and implementing the Time-based One-time Password (TOTP) algorithm specified in RFC 6238.
To use the two factor authentication, your user will have to install a Google Authenticator compatible app. Here are some that are currently available:
To start, we will create a fresh Laravel installation. Let’s install it in a folder called laravel-2fa
:
Set proper folder permissions:
For more detailed installation instructions, visit the documentation.
We can then start our server with the command:
Now our website will be available on http://localhost:8000
. It should look like this.
In order to manage the user data, we need to connect to a database. We will use MySQL for this tutorial, but it works the same for any other database system.
In the .env
file, edit the following lines according to your database setup.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
You should also update the following lines.
APP_NAME=Laravel 2FA Demo
APP_URL=http://localhost:8000
This is to give our application a name different from the default (Laravel) and also to update our base URL. You can choose any other URL depending on your setup, but take note and use the right base URL while following this tutorial.
Laravel ships with several pre-built authentication controllers and provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:
Create the database tables needed with:
If we visit our site, we will now see this. Notice LOGIN
and REGISTER
at the top of the screen.
.
We can then visit http://localhost:8000/register
to register a new user.
What we aim to achieve is this:
This way the QR code page is accessible ONLY once. This is for maximum security. If the user wants to set up the two-factor authentication again, they will have to repeat the flow and invalidate the old one.
To achieve this, we will put a step for setting up the Google Authenticator before registering the user in the database.
To make changes to the registration flow, we have to define the register method of the RegisterController
(you can find it at app/Http/Controllers/Auth/RegisterController
).
First, we need to install two packages.
If you are using Laravel 5.4 and below, you need to add PragmaRX\Google2FALaravel\ServiceProvider::class,
to your providers array, and 'Google2FA' => PragmaRX\Google2FALaravel\Facade::class,
to your aliases array in app/config/app.php
(Laravel 4.x) or config/app.php
(Laravel 5.x).
Next, we have to publish the config file using:
Next, we include the Request class at the top of our RegisterController
. This is so we can use the Request
class without using the full namespace.
Then we define the register
method of our RegisterController
like this.
We also need to create the view for displaying the QR code. Our method defines the view as google2fa.register
, so in resources/views
we will create a google2fa
folder and a file inside it called register.blade.php
.
So the full file path will be resources/views/google2fa/register.blade.php
.
Here are the contents of the file.
Now immediately after registration, the user is taken to a page with the relevant QR code and the SECRET in case they cannot scan the code themselves.
The page should look like this.
Unfortunately, we get an error when the user tries to proceed beyond this point, this is because we have not set up the route and controller action to handle the proper registration.
However, before we do that, we need to make space for the Google two-factor authentication secret in the users
table. For that, we create a migration.
The migration file should look like this.
The migration file tells our application to add a googel2fa_secret
column to our users table when we run it and to delete that column if we rollback the migration. Now we run our migrations again.
In this next step of the registration, we will need to make use of the register
method that we overrode, so in our RegisterController
, we change this:
to this:
Next, we create the complete-registration
route.
In routes/web.php
add the following line:
So, now we define the completeRegistration
method in our RegisterController
.
Unfortunately, the default Laravel authentication saves just the name, email, and password.
To include our google2fa_secret
we modify our create
method:
We have to also modify our User
model’s fillable
property to include the google2fa_secret
and also hide it whenever we cast it to an array or JSON.
Read about the fillable
property here.
Read about hiding attributes from casting here.
So we modify the following lines in the app/User.php
.
We can proceed with this, but for extra security, let us encrypt the google2fa_secret
so that our users are not compromised even if our database gets compromised.
In our User
model, we will add these extra methods.
To understand how the above methods work, read about Laravel accessors and mutators here.
Finally, users can now register seamlessly! A logged-in user should see this:
Everything we have done so far will be useless if we do not use it during the login flow. Since we are still using the default login flow, users only need their email and password.
Our aim is for users to first input their Google Authenticator code before they are allowed full access to the site.
The best way to implement this is to use a middleware. Thankfully, the pragmarx/google2fa-laravel
package ships with a middleware for this.
To use it, first, we add this to the routeMiddleware
array in app/Http/Kernel.php
.
With this, we can use 2fa
to refer to our middleware whenever we need to. Either in our route files or inside our controller classes.
Next, we define the view where the user enters the OTP after logging in. By default, it is configured to use the view at resources/views/google2fa/index.blade.php
. So we will create the view and add the following.
Next, we need a route to handle the submissions of the OTP. The middleware already checks for the OTP, so we just need a route to sit behind the middleware and redirect the user back to the original URL.
We can do that by adding this to routes/web.php
:
We created a route that responds to post requests to http://localhost:8000/2fa
and redirects to the previous URL. Since we put the route behind the 2fa
middleware, it will validate the OTP if it is contained in the request object.
Now, we can use the middleware to restrict any aspect of the application that requires it.
Read all about using middlewares here.
For example, in our HomeController
, we can change this:
to this
So that after logging in, when the user is redirected to /home
they have to first enter the one-time password from the google authenticator.
They will be presented with a form like this:
Once they enter the OTP, they will then be fully logged in.
That’s it! We’ve successfully added two-factor authentication with the Google Authenticator to our Laravel Application.
So you user feels like someone has access to his secret and will be able to generate the OTP, so he wants to get a new one.
You don’t want him calling you at 3 am or blaming you if something goes wrong, so you need to give them a link to re-authenticate.
To do this, let us define the route.
In routes/web.php
we’ll add:
Next, in HomeController
we’ll add the reauthenticate
method;
If you notice, we are using the same view as last time. So let us add some conditionals in the view to hide the registration messages.
Edit resources/views/google2fa/register.blade.php
:
So this time your user cannot log in. His phone may have been stolen, or he deleted the credentials unknowingly or some other thing.
Bottom line is, you have to generate a new secret for him.
I’ve found the best way to do this is to create an artisan command that will update the user secret and print it on the command line. We can then send the secret to the user to input in his app.
To create the command we run this:
Now we can go edit our command file at app/Console/Commands/ReAuthenticate.php
.
I’ve added comments to explain what the command does.
Read all about the creating console commands for the artisan console here.
To use it, we go to the terminal and run
It will prompt the user’s email and then ask for confirmation.
We can also pass the user’s email with the command by adding the --email
option.
To skip confirmation check, we can force the command using the --force
option
The new secret key generated will be printed to the console, so you can copy it and send it to your user so he can set up his app.
In this tutorial, we’ve seen how we can add two-factor authentication to a Laravel application. We modified both the registration and login flow and even dealt with a couple of edge cases.
If you want to get a Laravel 5.5 template with two-factor authentication already set up, you can clone the repository(Don’t forget to star it too). It was set up using the steps in this article.
As always, if you have any questions, suggestions, or comments, please leave them below.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!