Step by Step Guide to Create 2 Factor Authentication in Laravel

In this guide about creating 2Fa or factor authentication in laravel 11 or any other later version we are going to walk you through the whole drill.  So please make sure to follow these steps for installing Laravel, adding the 2FA package, configuring it, and integrating it into the login process. One of the biggest reason for Adding Two-Factor Authentication (2FA) to your Laravel app is very important especially in 2024 where every now and then everything connected to the internet gets attacked by DDoS and other types of hack attacks. This method enhances security by requiring an additional verification step during login. Here’s how you can set up 2FA using the pragmarx/google2fa-laravel package.

Step #1 Install Latest Laravel Version

First, make sure Laravel is installed on your system. Follow the official Laravel installation guide to set it up.

Step #2 Install the 2FA Package

We would use Composer to install the pragmarx/google2fa-laravel package . This package integrates Google Authenticator with Laravel, providing an easy-to-use 2FA solution.

composer require pragmarx/google2fa-laravel

Step #3 Configure the 2FA Package

After installation, publish the configuration file to tailor the 2FA settings to your application’s needs.

php artisan vendor:publish --provider="PragmaRX\\Google2FA\\Vendor\\Laravel\\ServiceProvider"

This will create a config/google2fa.php file. You can adjust settings like the length of one-time passwords (OTPs) and the number of attempts allowed.

Next, register the 2FA middleware in app/Http/Kernel.php:

use PragmaRX\Google2FA\Vendor\Laravel\Middlewares\Google2FA;

protected $routeMiddleware = [
    '2fa' => Google2FA::class,
];

This middleware will protect routes that require 2FA.

Step #4 Integrate 2FA into the Login Process

Modify the login flow to include a 2FA step. After verifying the user’s credentials, prompt for the OTP generated by the Google Authenticator app.

Add the following logic to your login controller:

public function login(Request $request)
{
    // Validate the user's credentials
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {

        // Check if the user has enabled 2FA
        if ($request->user()->google2fa_secret) {

            // Generate 2FA URL for the user
            $google2fa = app('pragmarx.google2fa');
            $QR_Image = $google2fa->getQRCodeInline(
                config('app.name'),
                $request->user()->email,
                $request->user()->google2fa_secret
            );

            // Show the 2FA view with QR code and input field for OTP
            return view('auth.2fa', ['QR_Image' => $QR_Image]);
        }

        // If no 2FA is enabled, proceed with the login
        return redirect()->intended('dashboard');
    }

    // Redirect back with error if credentials are incorrect
    return back()->withErrors(['email' => 'Invalid credentials.']);
}

 

This code snippet checks if the user has enabled 2FA. If they have, it generates a QR code for scanning with Google Authenticator and prompts the user to enter the OTP.

Step #5 We Must Verify The OTP

Now we MUST verify the OTP that has been provided by the user. In the same controller, add the following method:

public function verify2fa(Request $request)
{
    $google2fa = app('pragmarx.google2fa');
    $valid = $google2fa->verifyKey($request->user()->google2fa_secret, $request->input('otp'));

    if ($valid) {
        // Mark 2FA as verified and proceed to the intended page
        $request->session()->put('2fa_verified', true);
        return redirect()->intended('dashboard');
    }

    // Redirect back with error if OTP is invalid
    return back()->withErrors(['otp' => 'Invalid OTP.']);
}

This method checks the validity of the OTP. If valid, it grants access; otherwise, it redirects the user back with an error message.

Step #6 Protect Routes with 2FA

To secure specific routes with 2FA, apply the middleware in your routes file:

Route::group(['middleware' => ['auth', '2fa']], function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

This ensures that users must complete the 2FA step before accessing sensitive areas of your application. This guide provides a straightforward approach to adding Two-Factor Authentication to a Laravel app, ensuring enhanced security without unnecessary complexity. So this way without getting trapped in anything we can easily protect our apps and websites by just adding 2 factor authentication.