Web Security
Beginner
1 min read
Multi-Factor Authentication (MFA) Implementation
Example
<?php
// TOTP MFA with the pragmarx/google2fa-laravel package
// 1. Generate and store a secret key during MFA enrollment
use PragmaRX\Google2FALaravel\Facade as Google2FA;
// Enrollment: generate secret and display QR code
$secret = Google2FA::generateSecretKey(32);
// Store $secret encrypted in the users table (never plain-text)
$user->update(['totp_secret' => encrypt($secret)]);
$qrCodeUrl = Google2FA::getQRCodeUrl(
config('app.name'),
$user->email,
$secret
);
// Render QR code as SVG or PNG for the user to scan
// 2. Verify a code at login
function verifyTOTP(User $user, string $code): bool
{
$secret = decrypt($user->totp_secret);
// Allow 1 window (30s) of drift for clock skew
return Google2FA::verifyKey($secret, $code, 1);
}
// 3. Mark session as MFA-verified
if (verifyTOTP($user, $request->input('totp_code'))) {
session(['mfa_verified' => true, 'mfa_verified_at' => now()->timestamp]);
return redirect()->intended('/dashboard');
}
// 4. Middleware to require MFA on sensitive routes
// if (!session('mfa_verified')) redirect('/mfa/challenge');
// Recovery codes — generate 8 one-time codes at enrollment
$recoveryCodes = collect(range(1, 8))->map(fn() => bin2hex(random_bytes(10)))->all();
// Store hashed recovery codes; delete after use
Related Resources
Web Security Reference
Complete tag & property list
Web Security How-To Guides
Step-by-step practical guides
Web Security Exercises
Practice what you've learned
More in Web Security