How to setup Google's Two Factor Authentication in Laravel

  • 04-09-2022
  • 4675
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

How to set up google's two-factor authentication in laravel; With the help of google authentication, we will integrate it into our laravel application. To integrate 2fa into our application we need to install some of the packages that will help us to develop an app.

2fa code google authenticator; is the secure authentication system to make the user auth system very secure from the public. you can add an extra layer of security to your account in the case of user password is stolen.

Laravel 9 google 2fa authentication tutorial and authentication is the PHP implementation of the google two-factor authentication. After two-factor verification, you can sign in to your account with your latest password generated for your account.

Laravel 2fa google login is an important security measure that adds your app's second layer of protection in addition to your account password. adding this security layer makes it much harder for hackers to break into your account.

Step 1. Create New Laravel Project

Create a laravel 9 project using the below-provided command, open your cmd command line or your system terminal and paste the below-provided command in the terminal, and hit enter. It will take some time to install the project.

composer create-project laravel/laravel 2fa

REST API Authentication With Laravel Passport

Go to your project directory using "cd" and then give your project name and hit enter in your terminal.

cd 2fa

Step 2. Install Laravel UI

Once create a new laravel project, we need to config the mail setting to generate your mail configuration from your mail provider and config it in-app.

Use below command and install laravel ui in app.

composer require laravel/ui
Add Bootstrap:

Next, create auth with bootstrap help, and use the below command to install it in your app.

php artisan ui bootstrap --auth
Npm Install:

You may be suggested, if not then run below-provided command and install npm in app. and bind npm scrip using npm run dev command.

npm install && npm run dev

Step 3. Migration and Model

Add a "google2fa_secret" column in the user's table also adds this column name in the user model in the fillable property.

database/migrations/2014_10_12_000000_create_users_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
        * Run the migrations.
        *
        * @return void
        */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->text('google2fa_secret');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
        * Reverse the migrations.
        *
        * @return void
        */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Add that column name in model-protected fillable property also.

Laravel 9 Create Custom Auth Guard Multi Login Authentication System Tutorial

One more thing we will settle here. We will store "encrypt" while store secret key and "decrypt" when you retrieve data from the users table. For doing this thing adds an attribute property as per in this model given.

You can see google2faSecret() method at the end this this user model. add just like this.

app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
        * The attributes that are mass assignable.
        *
        * @var array
        */
    protected $fillable = [
        'name',
        'email',
        'password',
        'google2fa_secret'
    ];

    /**
        * The attributes that should be hidden for serialization.
        *
        * @var array
        */
    protected $hidden = [
        'password',
        'remember_token',
        'google2fa_secret'
    ];

    /**
        * The attributes that should be cast.
        *
        * @var array
        */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

        public function setGoogle2faSecretAttribute($value)
    {
            $this->attributes['google2fa_secret'] = encrypt($value);
    }

    public function getGoogle2faSecretAttribute($value)
    {
        return decrypt($value);
    }
}

If you haven't set up your database with the application please go to the .env file and set up yopur database configuration, Then after running the below suggested command it will migrate all tables in your database.

php artisan migrate

Step 4. Install 2fa Package

Here, In this step we need to install two composers, the first composer for the google authentication package for the PHP laravel and another for the Qrcode generate barcode.

composer require pragmarx/google2fa-laravel

For the QR code generation. install package use below given command.

composer require bacon/bacon-qr-code

Got giving globally namespace just register in the app.php file in the config folder, register namespace and service provider.

config/app.php
'providers' => [
    ....
    PragmaRX\Google2FALaravel\ServiceProvider::class,
],

'aliases' => [
    ....
    'Google2FA' => PragmaRX\Google2FALaravel\Facade::class,
],

Run the below-given command and publish the config file for the google authentication.

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

Step 5. Register 2fa Middleware in Kernel.php

Now, register 2fa middleware in "kernel.php" file. this will check HTTP request with 2fa authentication.

app/Http/kernel.php
protected $routeMiddleware = [
    ...
    '2fa' => \PragmaRX\Google2FALaravel\Middleware::class,
];

Step 6. Setup RegisterController

This is the registration controller, I have configured already. so you just need to copy all the code and paste it into your application.

Laravel-9 Multi Authentication Guard Passport API Example

app/Http/Controllers/Auth/RegisterController.php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;

use PragmaRX\Google2FAQRCode\Google2FA;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers {
        register as registration;
    }

    /**
        * Where to redirect users after registration.
        *
        * @var string
        */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
        * Create a new controller instance.
        *
        * @return void
        */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
        * Get a validator for an incoming registration request.
        *
        * @param  array  $data
        * @return \Illuminate\Contracts\Validation\Validator
        */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
        * Create a new user instance after a valid registration.
        *
        * @param  array  $data
        * @return \App\Models\User
        */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'google2fa_secret' => $data['google2fa_secret'],
        ]);
    }

        /**
        * Write code on Method
        *
        * @return response()
        */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();
        $google2fa = app('pragmarx.google2fa');
        $registration_data = $request->all();
        $registration_data["google2fa_secret"] = $google2fa->generateSecretKey();
        $request->session()->flash('registration_data', $registration_data);
        // $QR_Image = $google2fa->getQRCodeInline(
        //     config('app.name'),
        //     $registration_data['email'],
        //     $registration_data['google2fa_secret']
        // );

        $twoFa = new Google2FA();
        $key = $twoFa->generateSecretKey();
        $QR_Image = $twoFa->getQRCodeInline(
            config('app.name'),
            $registration_data['email'],
            $registration_data['google2fa_secret']
        );
        
        return view('google2fa.register', ['QR_Image' => $QR_Image, 'secret' => $registration_data['google2fa_secret']]);
    }
    /**
        * Write code on Method
        *
        * @return response()
        */
    public function completeRegistration(Request $request)
    {        
        $request->merge(session('registration_data'));
        return $this->registration($request);
    }
}

Step 7. Create the view to display the QR code

This blade file will generate a QR code, this QR code you need to scan in your mobile google authentication app. once you scan the given QR code you will get an OTP code in your mobile on in google app.

resources/views/google2fa/register.blade.php
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12 mt-4">
            <div class="card card-default">
                <h4 class="card-heading text-center mt-4">Set up Google Authenticator</h4>

                <div class="card-body" style="text-align: center;">
                    <p>Set up your two factor authentication by scanning the barcode below. Alternatively, you can use the code <strong>{{ $secret }}</strong></p>
                    <div>
                        <img src="{{ $QR_Image }}">
                    </div>
                    <p>You must set up your Google Authenticator app before continuing. You will be unable to login otherwise</p>
                    <div>
                        <a href="{{ route('complete.registration') }}" class="btn btn-primary">Complete Registration</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 8. Define Route

Add route as per in this example below given just copy give route and paste in your application. also, you can see you I used an authentication middleware that I already registered in the kernel file.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\HomeController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

// 2fa middleware
Route::middleware(['2fa'])->group(function () {
    // HomeController
    Route::get('/home', [HomeController::class, 'index'])->name('home');
    Route::post('/2fa', function () {
        return redirect(route('home'));
    })->name('2fa');
});
Route::get('/complete-registration', [RegisterController::class, 'completeRegistration'])->name('complete.registration');

Step 9. Create Index View File

After all that, users can log in, there will see a QR code, and also there will be a manually input code enter code. You users are not able to scan QR codes they can also input them manually.

So once you scan a QR code or address secret code, you just open your google authentication app and get OTP from your app.

This is the blade file OTP screen code just copy the whole code and paste into your blade file.

resources/views/google2fa/index.blade.php
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center align-items-center " style="height: 70vh;S">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading font-weight-bold">Register</div>
                <hr>
                @if($errors->any())
                    <div class="col-md-12">
                        <div class="alert alert-danger">
                            <strong>{{$errors->first()}}</strong>
                        </div>
                    </div>
                @endif

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="{{ route('2fa') }}">
                        {{ csrf_field() }}

                        <div class="form-group">
                            <p>Please enter the  <strong>OTP</strong> generated on your Authenticator App. <br> Ensure you submit the current one because it refreshes every 30 seconds.</p>
                            <label for="one_time_password" class="col-md-4 control-label">One Time Password</label>


                            <div class="col-md-6">
                                <input id="one_time_password" type="number" class="form-control" name="one_time_password" required autofocus>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4 mt-3">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 10. Run Development Server

After doing all steps successfully, copy the below-given command and paste it into your project terminal to start the development server.

php artisan serve

Next, open your browser and run the below-given URL in your browser to get the output of your tutorial integration.

http://localhost:8000/register

Microsoft Authentication Implement on Laravel App


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :