the best way to use composer require pragmarx/google2fa in laravel
- User
the best way to use composer require pragmarx/google2fa in laravel
Assistant
the best way to use composer require pragmarx/google2fa in laravel
To use pragmarx/google2fa in Laravel for two-factor authentication, here's the complete setup process:
composer require pragmarx/google2fa
Publish the configuration file:
php artisan vendor:publish --provider="PragmaRX\Google2FA\Vendor\Laravel\ServiceProvider"
Create a migration to add 2FA fields to your users table:
php artisan make:migration add_two_factor_to_users_table
In the migration file:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('google2fa_secret')->nullable();
$table->boolean('google2fa_enabled')->default(false);
});
}
Run the migration:
php artisan migrate
Add the 2FA fields to your User model's $fillable array:
protected $fillable = [
// ... other fields
'google2fa_secret',
'google2fa_enabled',
];
protected $hidden = [
// ... other fields
'google2fa_secret',
];
Create a controller for 2FA management:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PragmaRX\Google2FA\Google2FA;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\Image\ImagickImageBackEnd;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
class TwoFactorController extends Controller
{
public function enable(Request $request)
{
$google2fa = new Google2FA();
$user = auth()->user();
// Generate secret key
$secret = $google2fa->generateSecretKey();
// Store secret temporarily (you might want to use session)
session(['2fa_secret' => $secret]);
// Generate QR code
$qrCodeUrl = $google2fa->getQRCodeUrl(
config('app.name'),
$user->email,
$secret
);
$renderer = new ImageRenderer(
new RendererStyle(400),
new ImagickImageBackEnd()
);
$writer = new Writer($renderer);
$qrCode = base64_encode($writer->writeString($qrCodeUrl));
return view('auth.2fa-setup', compact('qrCode', 'secret'));
}
public function verify(Request $request)
{
$request->validate([
'one_time_password' => 'required|numeric',
]);
$google2fa = new Google2FA();
$secret = session('2fa_secret');
$valid = $google2fa->verifyKey($secret, $request->one_time_password);
if ($valid) {
$user = auth()->user();
$user->update([
'google2fa_secret' => $secret,
'google2fa_enabled' => true,
]);
session()->forget('2fa_secret');
return redirect()->route('dashboard')->with('success', '2FA enabled successfully!');
}
return back()->withErrors(['one_time_password' => 'Invalid verification code.']);
}
public function authenticate(Request $request)
{
$request->validate([
'one_time_password' => 'required|numeric',
]);
$google2fa = new Google2FA();
$user = auth()->user();
$valid = $google2fa->verifyKey($user->google2fa_secret, $request->one_time_password);
if ($valid) {
session(['2fa_verified' => true]);
return redirect()->intended('dashboard');
}
return back()->withErrors(['one_time_password' => 'Invalid verification code.']);
}
}
Create middleware to enforce 2FA verification:
php artisan make:middleware Ensure2FA
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Ensure2FA
{
public function handle(Request $request, Closure $next)
{
$user = auth()->user();
if ($user && $user->google2fa_enabled && !session('2fa_verified')) {
return redirect()->route('2fa.form');
}
return $next($request);
}
}
Register the middleware in app/Http/Kernel.php:
protected $routeMiddleware = [
// ... other middleware
'2fa' => \App\Http\Middleware\Ensure2FA::class,
];
Add routes to web.php:
Route::middleware(['auth'])->group(function () {
Route::get('/2fa/enable', [TwoFactorController::class, 'enable'])->name('2fa.enable');
Route::post('/2fa/verify', [TwoFactorController::class, 'verify'])->name('2fa.verify');
Route::get('/2fa/authenticate', function () {
return view('auth.2fa-authenticate');
})->name('2fa.form');
Route::post('/2fa/authenticate', [TwoFactorController::class, 'authenticate'])->name('2fa.authenticate');
});
// Protected routes
Route::middleware(['auth', '2fa'])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
Create the setup view (resources/views/auth/2fa-setup.blade.php):
<div class="container">
<h2>Setup Two-Factor Authentication</h2>
<p>Scan this QR code with your authenticator app:</p>
<img src="data:image/png;base64,{{ $qrCode }}" alt="QR Code">
<p>Or enter this secret manually: <code>{{ $secret }}</code></p>
<form method="POST" action="{{ route('2fa.verify') }}">
@csrf
<div class="form-group">
<label>Enter verification code:</label>
<input type="text" name="one_time_password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Verify & Enable</button>
</form>
</div>
This setup provides a complete 2FA implementation using Google Authenticator or similar TOTP apps. Users can enable 2FA, and protected routes will require verification after login.