Blog Details
How to create Two-Factor Authentication with Laravel

Introduction:
Two-factor authentication (2FA) is a security feature that adds an extra layer of protection to user accounts by requiring users to provide two different authentication factors to log in. In this article, we will explore how to create two-factor authentication with Laravel, a popular PHP web framework.
Step 1: Install Laravel
First, you need to install Laravel on your machine. You can follow the official documentation for installation instructions.
Step 2: Install Two-Factor Authentication Package
Next, you need to install a two-factor authentication package for Laravel. There are several packages available, but for this tutorial, we will use the “laravel-2fa” package, which provides a simple and easy-to-use implementation of 2FA.
You can install the package using Composer by running the following command:
composer require pragmarx/google2fa-laravel
Step 3: Configure 2FA
Once the package is installed, you need to configure it in your Laravel application. First, you need to publish the configuration file by running the following command:
php artisan vendor:publish --provider="PragmaRX\Google2FA\Vendor\Laravel\ServiceProvider"
This command will create a “config/google2fa.php” file in your application. You can modify this file to customize the 2FA settings, such as the length of the one-time passwords and the number of allowed attempts.
Next, you need to add the 2FA middleware to your application’s authentication system. You can do this by adding the following code to your “app/Http/Kernel.php” file:
use PragmaRX\Google2FA\Vendor\Laravel\Middlewares\Google2FA;
protected $routeMiddleware = [
'2fa' => Google2FA::class,
];
This code registers the “2fa” middleware, which you can use to protect routes that require 2FA authentication.
Step 4: Add 2FA to Login Process
Now, you need to modify the login process to require 2FA authentication after the user enters their credentials. You can do this by adding the following code to your “app/Http/Controllers/Auth/LoginController.php” file:
use Illuminate\Http\Request;
use PragmaRX\Google2FA\Google2FA;
public function authenticated(Request $request, $user)
{
if ($user->uses_two_factor_auth) {
$google2fa = new Google2FA();
if ($request->session()->has('2fa_passed')) {
$request->session()->forget('2fa_passed');
}
$request->session()->put('2fa:user:id', $user->id);
$request->session()->put('2fa:auth:attempt', true);
$request->session()->put('2fa:auth:remember', $request->has('remember'));
$otp_secret = $user->google2fa_secret;
$one_time_password = $google2fa->getCurrentOtp($otp_secret);
return redirect()->route('2fa')->with('one_time_password', $one_time_password);
}
return redirect()->intended($this->redirectPath());
}
This code checks if the user has 2FA enabled, and if so, generates a one-time password using the user’s Google Authenticator secret key. It then stores the user ID and some authentication information in the session and redirects the user to a 2FA verification page.
Step 5: Create 2FA Verification Page
Next, you need to create a 2FA verification page where the user can enter their one-time password. You can create a new view file called “2fa.blade.php” in your “resources/views” directory and add the following code to display a form for entering the one-time password:
@extends('layouts.app')
@section('content')
{{ __('Two Factor Authentication') }}
{{ __('Please enter your one-time password to complete your login.') }}
@csrf
{{ __('One Time Password') }}
@error('one_time_password')
{{ $message }}
@enderror
{{ __('Verify') }}
@endsection
This code creates a form with a single field for entering the one-time password, and a “Verify” button to submit the form.
Step 6: Verify 2FA Authentication
Finally, you need to add a route and controller method to verify the 2FA authentication. You can create a new route in your “routes/web.php” file like this:
Route::get('/2fa', 'Auth\TwoFactorController@show')->name('2fa');
Route::post('/2fa', 'Auth\TwoFactorController@verify')->name('2fa.verify');
This code creates two routes, one for showing the 2FA verification page and one for verifying the one-time password.
Next, you need to create a new controller called “TwoFactorController” using the following command:
php artisan make:controller Auth/TwoFactorController
Then, you can add the following code to the controller to handle the 2FA verification:
use Illuminate\Http\Request;
use PragmaRX\Google2FA\Google2FA;
use Illuminate\Validation\ValidationException;
public function show(Request $request)
{
return view('auth.2fa');
}
public function verify(Request $request)
{
$request->validate([
'one_time_password' => 'required|string',
]);
$user_id = $request->session()->get('2fa:user:id');
$remember = $request->session()->get('2fa:auth:remember', false);
$attempt = $request->session()->get('2fa:auth:attempt', false);
if (!$user_id || !$attempt) {
return redirect()->route('login');
}
$user = User::find($user_id);
if (!$user || !$user->uses_two_factor_auth) {
return redirect()->route('login');
}
$google2fa = new Google2FA();
$otp_secret = $user->google2fa_secret;
if (!$google2fa->verifyKey($otp_secret, $request->one_time_password)) {
throw ValidationException::withMessages([
'one_time_password' => [__('The one time password is invalid.')],
]);
}
$guard = config('auth.defaults.guard');
$credentials = [$user->getAuthIdentifierName() => $user->getAuthIdentifier(), 'password' => $user->getAuthPassword()];
if ($remember) {
$guard = config('auth.defaults.remember_me_guard', $guard);
}
if ($attempt) {
$guard = config('auth.defaults.attempt_guard', $guard);
}
if (Auth::guard($guard)->attempt($credentials, $remember)) {
$request->session()->remove('2fa:user:id');
$request->session()->remove('2fa:auth:remember');
$request->session()->remove('2fa:auth:attempt');
return redirect()->intended('/');
}
return redirect()->route('login')->withErrors([
'password' => __('The provided credentials are incorrect.'),
]);
}
This code first validates the one-time password field and then checks if the user has enabled 2FA authentication. If the user has not enabled 2FA, or the one-time password is invalid, the user is redirected to the login page with an error message.
If the user has enabled 2FA and the one-time password is valid, the user is authenticated and redirected to the home page.
Conclusion
In this tutorial, you learned how to create two-factor authentication with Laravel using the Google Authenticator library. Two-factor authentication adds an extra layer of security to your application, making it more difficult for attackers to gain access to your users’ accounts. By following the steps in this tutorial, you can easily add two-factor authentication to your Laravel application and keep your users’ accounts secure.