Example Laravel project with Google Authenticator 2FA
- laravel/ui to install the frontend scaffolding
- pragmarx/google2fa-laravel to enable Google 2FA secret and QR code
app/Http/Controllers/Auth/Google2FAController.php
app/Http/Controllers/Auth/LoginController.php
database/migrations/2019_10_18_001813_add_google2fa_secret_to_users_table.php
resources/views/auth/google2fa/activate.blade.php
resources/views/auth/google2fa/deactivate.blade.php
resources/views/auth/google2fa/login.blade.php
routes/web.php
-
Create Laravel 6 project
laravel new my-project cd my-project
-
Install the Laravel frontend scaffolding
composer require laravel/ui --dev php artisan ui vue --auth npm install & npm run dev
-
Install pragmarx/google2fa-laravel to enable 2FA
composer require pragmarx/google2fa-laravel --dev
-
Publish the config file if custom settings are required (optional)
php artisan vendor:publish --provider="PragmaRX\Google2FALaravel\ServiceProvider"
-
Create database migration to store 2FA secret
php artisan make:migration add_google2fa_secret_to_users_table
Edit migration file
Schema::table('users', function (Blueprint $table) { - // + $table->string('google2fa_secret')->nullable()->after('password'); });
Schema::table('users', function (Blueprint $table) { - // + $table->dropColumn('google2fa_secret'); });
-
Edit
routes/web.php
+ Route::get('/2fa/activate', [Google2FAController::class, 'activate2FA'])->name('2fa.activate'); + Route::post('/2fa/activate', [Google2FAController::class, 'assign2FA']);
-
Activation flow. See
app/Http/Controllers/Auth/Google2FAController.php
- Generate secret key
- Save to session temporarily
- Generate QR code
- Show QR code and secret to user
- User install Google 2FA app on mobile device (if not installed)
- User scan QR code (or, manually add secret)
- User input 2FA code to verify
- If 2FA code is not verified, show error and repeat step iv
- If 2FA code is verified, save 2FA secret to user - activation is complete
-
Add view to activate 2FA. See
resources/views/auth/google2fa/activate.blade.php
-
Edit
routes/web.php
+ Route::get('/2fa/deactivate', [Google2FAController::class, 'deactivate2FA'])->name('2fa.deactivate');
-
Delete 2FA secret from user. See
app/Http/Controllers/Auth/Google2FAController.php
-
Add view to deactivate 2FA. See
resources/views/auth/google2fa/deactivate.blade.php
-
Edit
routes/web.php
+ Route::get('/2fa/login', [Google2FAController::class, 'login2FA'])->name('2fa.login'); + Route::post('/2fa/login', [Google2FAController::class, 'verify2FA']);
-
Redirect user to 2FA form after login with password. See
app/Http/Controllers/Auth/LoginController.php
-
Verify 2FA code, and login user if successful. See
app/Http/Controllers/Auth/Google2FAController.php
-
Add views to login with 2FA. See
resources/views/auth/google2fa/login.blade.php