Back to Homepage

Add Google Authenticator in Laravel

3 min read

Tags:

Laravel Security
Add Google Authenticator in Laravel

While Laravel provides a robust authentication scaffold, the traditional email and password method is increasingly becoming susceptible to cyber threats like SQL injections, phishing attacks, and data breaches. To counter these threats, the concept of two-factor authentication (2FA) was introduced. In this context, we will explore how to implement Google Authenticator in Laravel, a popular PHP framework.

Defining Two-Factor Authentication (2FA)

Two-Factor Authentication (2FA) enhances access security by requiring two methods to verify user identities. The first factor is usually a password, something that the user should exclusively know. The second factor is an additional layer of security, typically something that the user doesn't readily have or is not constant. It could be biometrics (fingerprint), voice pattern recognition, iris scan, or One-Time Passwords (OTPs).

Understanding One-Time Passwords (OTPs)

An OTP is an automatically generated set of characters that authorizes a user for a specific action and can only be used once. It can be counter-based or time-based. After the correct password is provided in the login form, the user is prompted for an OTP, which can be implemented in several ways such as hardware tokens, OTP sent via SMS, or the Google Authenticator.

Installation

Install the Necessary Package: Begin by installing the pragmarx/google2fa-laravel package via Composer:

composer require pragmarx/google2fa-laravel

Publish the Configuration: After the installation, publish the configuration file to customize settings if needed:

php artisan vendor:publish --provider="PragmaRX\Google2FALaravel\ServiceProvider"

Update the Users Migration: Create a migration to add a google2fa_secret column to the users table:

php artisan make:migration add_google2fa_secret_to_users_table --table=users

Update the migration file as follows:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('google2fa_secret')->nullable();
    });
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('google2fa_secret');
    });
}

Run the Migration: Apply the migration with the following command:

php artisan migrate

Create a Controller for 2FA Operations: Generate a new controller named Google2FAController:

php artisan make:controller Google2FAController

Define methods for displaying the QR code, enabling 2FA, and verifying the OTP:

use Illuminate\Http\Request;
use PragmaRX\Google2FALaravel\Google2FA;

class Google2FAController extends Controller
{
    public function showQR()
    {
        $google2fa_url = (new Google2FA())->getQRCodeInline(
            config('app.name'),
            auth()->user()->email,
            auth()->user()->google2fa_secret
        );

        return view('google2fa.qr', ['google2fa_url' => $google2fa_url]);
    }

    public function enable2FA(Request $request)
    {
        $user = auth()->user();
        $user->google2fa_secret = (new Google2FA())->generateSecretKey();
        $user->save();

        return redirect()->route('google2fa.qr');
    }

    public function verify2FA(Request $request)
    {
        $request->validate(['otp' => 'required|digits:6']);

        $google2fa = new Google2FA();
        $valid = $google2fa->verifyKey(auth()->user()->google2fa_secret, $request->otp);

        if ($valid) {
            return redirect()->route('dashboard');
        }

        return back()->withErrors(['otp' => 'Invalid OTP']);
    }
}

Update Routes: Define routes for your 2FA operations in the web.php file:

Route::get('google2fa', [Google2FAController::class, 'showQR'])->name('google2fa.qr');
Route::post('google2fa/enable', [Google2FAController::class, 'enable2FA'])->name('google2fa.enable');
Route::post('google2fa/verify', [Google2FAController::class, 'verify2FA'])->name('google2fa.verify');

With the successful implementation of Google Authenticator in Laravel, you've built an authentication system that not only provides an additional layer of security but also enhances the user experience. For any further questions or clarifications, feel free to drop your comments or reach out on Twitter.

Follow @LaravelSage on X → Follow @LaravelSage on Facebook →
Aniket Singh

Aniket Singh

View All Articles

Full-stack developer with a knack for Merging creativity with technical expertise for standout solutions.

Related Articles

data_forget Helper for Laravel

data_forget Helper for Laravel

Since Laravel version 10.15, there is a new utility function called data_forget that allows you to remove keys from an array or object using a "dot" notation.

Laravel Tenant Application with Tenancy

Laravel Tenant Application with Tenancy

You can make your Laravel app multi-tenant using the Tenancy for Laravel Tenant package. This tenancy package lets you make any Laravel application multi-tenant without rewriting it.

Top Laravel Packages for Building Powerful Applications

Top Laravel Packages for Building Powerful Applications

Are you ready to take your Laravel skills to the next level and build extraordinary applications? Look no further! In this blog post, we will unveil a treasure trove of top packages that will revolutionize your development process.

Subscribe for 20+ new Laravel tutorials every week

You can unsubscribe at any time. You'll also get -20% off my courses!

© 2024

 

Laravel Sage

   |    Privacy Policy