Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I integrate Google Authenticator with Laravel's two-factor authentication


How can I integrate Google Authenticator with Laravel's two-factor authentication


To integrate Google Authenticator with Laravel's two-factor authentication, you can follow these steps:

Step 1: Install Required Packages

1. Google2FA: This package provides functionalities for generating secret keys, validating user-provided TOTP codes, and ensuring code validity within a specific time window. Install it using Composer:

bash
   composer require pragmarx/google2fa-laravel
   

2. Bacon/Bacon-QR-Code: This package provides functionalities for generating QR codes. Install it using Composer:

bash
   composer require bacon/bacon-qr-code
   

Step 2: Configure the Packages

1. Google2FA Configuration:
- In your `config/google2fa.php` file, set the `secret_key_length` to the desired length for the secret keys.
- Set the `time_step` to the time interval (in seconds) between each one-time password.

2. Publish Configuration and Migration Files:
- Run the following command to publish the configuration and migration files:

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

3. Run Database Migrations:
- Run the following command to add the necessary columns to the `users` table:

bash
   php artisan migrate
   

Step 3: Update User Model

1. Add Google2FA Secret:
- In your `User` model, add the `google2fa_secret` column and encrypt it:

php
   use Illuminate\Database\Eloquent\Factories\HasFactory;
   use Illuminate\Foundation\Auth\User as Authenticatable;
   use Illuminate\Notifications\Notifiable;
   use Laravel\Sanctum\HasApiTokens;
   use Illuminate\Database\Eloquent\Casts\Attribute;

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

       protected $fillable = [
           'name',
           'email',
           'password',
           'google2fa_secret',
       ];

       protected $hidden = [
           'password',
           'remember_token',
       ];

       protected $casts = [
           'email_verified_at' => 'datetime',
       ];

       protected function google2faSecret(): Attribute
       {
           return new Attribute(
               get: fn ($value) => decrypt($value),
               set: fn ($value) => encrypt($value),
           );
       }
   }
   

Step 4: Create Routes

1. Add Routes for 2FA:
- In your `routes/web.php` file, add the necessary routes for enabling and disabling two-factor authentication:

php
   Route::get('/2fa/enable', 'TwoFactorAuthenticationController@enable');
   Route::get('/2fa/disable', 'TwoFactorAuthenticationController@disable');
   

Step 5: Implement Two-Factor Authentication Logic

1. Enable Two-Factor Authentication:
- In your `TwoFactorAuthenticationController`, add the logic to enable two-factor authentication:

php
   public function enable(Request $request): RedirectResponse
   {
       $user = $request->user();
       if ($user->hasEnabledTwoFactorAuthentication()) {
           return back()->with('status', 'Two-factor authentication is already enabled');
       }
       $user->enableTwoFactorAuthentication();
       return redirect()->route('account.two-factor-authentication.confirm.show');
   }
   

2. Disable Two-Factor Authentication:
- In your `TwoFactorAuthenticationController`, add the logic to disable two-factor authentication:

php
   public function disable(Request $request): RedirectResponse
   {
       $request->user()->disableTwoFactorAuthentication();
       return back()->with('status', 'Two-factor authentication disabled successfully');
   }
   

Step 6: Implement User Interface

1. Create Views for 2FA:
- Create views for enabling and disabling two-factor authentication:

php
   // resources/views/auth/google2fa/activate.blade.php
   // resources/views/auth/google2fa/deactivate.blade.php
   

Step 7: Implement QR Code Generation

1. Generate QR Code:
- In your `TwoFactorAuthenticationController`, generate the QR code for the user:

php
   public function show(Request $request): View|RedirectResponse
   {
       $user = $request->user();
       if ($user->hasEnabledTwoFactorAuthentication()) {
           return back()->with('status', 'Two-factor authentication is already enabled');
       }
       if (!$user->two_factor_secret) {
           return back()->with('status', 'Two-factor authentication is not enabled');
       }
       return view('account.two-factor-confirmation.show', [
           'qrCodeSvg' => $user->twoFactorQrCodeSvg(),
           'setupKey' => $user->two_factor_secret,
       ]);
   }
   

Step 8: Implement Two-Factor Authentication Challenge

1. Challenge View:
- Create a view for the two-factor authentication challenge:

php
   // resources/views/auth/google2fa/login.blade.php
   

2. Challenge Logic:
- In your `LoginController`, add the logic to redirect the user to the two-factor authentication challenge:

php
   public function login(Request $request): RedirectResponse
   {
       // do login stuff...
       return redirect()->route('two-factor-challenge.create');
   }
   

Step 9: Implement Two-Factor Authentication Confirmation

1. Confirmation View:
- Create a view for the two-factor authentication confirmation:

php
   // resources/views/auth/google2fa/confirm.blade.php
   

2. Confirmation Logic:
- In your `TwoFactorAuthenticationController`, add the logic to confirm two-factor authentication:

php
   public function confirm(Request $request): RedirectResponse
   {
       $request->validate([
           'code' => ['required', 'string'],
       ]);
       $request->user()->confirmTwoFactorAuthentication($request->code);
       return redirect()->route('account.two-factor-authentication.recovery-codes.index')->with('status', 'Two-factor authentication successfully confirmed');
   }
   

By following these steps, you can integrate Google Authenticator with Laravel's two-factor authentication.

Citations:
[1] https://www.itsolutionstuff.com/post/laravel-google-2fa-authentication-tutorial-exampleexample.html
[2] https://github.com/emargareten/two-factor-laravel
[3] https://github.com/brandonlim-hs/example-laravel-google-authenticator
[4] https://www.youtube.com/watch?v=_JrH1X8LJ6I
[5] https://stackoverflow.com/questions/76985600/laravel-google-authenticator-2fa-verify-successful-but-unable-to-redirect-to-h