1. Go to this page and download the library: Download webmonks/laravel-2fa library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
webmonks / laravel-2fa example snippets
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use WebMonks\Laravel2FA\Contracts\TwoFactorAuthenticatable;
use WebMonks\Laravel2FA\Traits\HasTwoFactorAuthentication;
class User extends Authenticatable implements TwoFactorAuthenticatable
{
use HasTwoFactorAuthentication;
// Your existing model code...
}
// Protect routes (in routes/web.php)
Route::group(['middleware' => ['auth', '2fa']], function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::get('/sensitive-data', [DataController::class, 'show']);
});
// Enable 2FA for users (in your controller)
use WebMonks\Laravel2FA\Facades\TwoFactor;
// Email OTP (works immediately - zero configuration needed)
TwoFactor::enable($user, 'email');
// TOTP/Google Authenticator
TwoFactor::enable($user, 'totp');
$qrCodeUrl = TwoFactor::getTotpQrCodeUrl($user); // Show this QR to user
// Day 1: Email OTP (works immediately)
TwoFactor::enable($user, 'email');
TwoFactor::generateCode($user, 'email'); // Sends via Laravel Mail
// Day 30: Add SMS when ready
// .env: TWILIO_SID=xxx TWILIO_TOKEN=yyy TWILIO_FROM=+1234567890
TwoFactor::setPhoneNumber($user, '+15551234567');
TwoFactor::enable($user, 'sms');
// Day 60: Add WhatsApp for global users
TwoFactor::enable($user, 'whatsapp');
TwoFactor::generateCode($user, 'whatsapp');
// Day 90: Add Voice calls for accessibility
TwoFactor::enable($user, 'voice');
TwoFactor::generateCode($user, 'voice'); // Multi-language support
// Day 120: Add Push notifications for mobile apps
TwoFactor::enable($user, 'push');
TwoFactor::registerPushDevice($user, $fcmToken, 'android');
// Day 150: Add TOTP for power users
TwoFactor::enable($user, 'totp');
$qrCode = TwoFactor::getTotpQrCodeUrl($user);
// Day 180: Add device trust and recovery codes
$recoveryCodes = TwoFactor::generateRecoveryCodes($user);
TwoFactor::trustDevice($user, $deviceFingerprint);
use WebMonks\Laravel2FA\Facades\TwoFactor;
// Enable email 2FA (works immediately with Laravel Mail)
TwoFactor::enable($user, 'email');
// Generate and send code
TwoFactor::generateCode($user, 'email');
// User receives: "Your verification code is: 123456"
// Verify code
$isValid = TwoFactor::verifyCode($user, '123456', 'email');
// Check status
$isEnabled = TwoFactor::isEnabled($user, 'email');
// Set user's phone number
TwoFactor::setPhoneNumber($user, '+15551234567');
// Enable SMS 2FA
TwoFactor::enable($user, 'sms');
// Generate and send SMS
$sent = TwoFactor::generateCode($user, 'sms');
if ($sent) {
return response()->json(['message' => 'SMS sent to your phone']);
}
// Verify SMS code
$isValid = TwoFactor::verifyCode($user, $request->input('code'), 'sms');
// Enable TOTP
TwoFactor::enable($user, 'totp');
// Get QR code URL for setup
$qrCodeUrl = TwoFactor::getTotpQrCodeUrl($user);
// Display this QR code to user for scanning with Google Authenticator
// Get setup key (alternative to QR code)
$setupKey = TwoFactor::getTotpSecretKey($user);
// Verify TOTP code
$isValid = TwoFactor::verifyCode($user, '123456', 'totp');
// Generate recovery codes
$codes = TwoFactor::generateRecoveryCodes($user);
// Returns: ['a1b2c3d4e5', 'f6g7h8i9j0', ...] (8 codes by default)
// Show codes to user for safe storage
foreach ($codes as $code) {
echo "Recovery code: {$code}\n";
}
// Verify recovery code
$isValid = TwoFactor::verifyRecoveryCode($user, 'a1b2c3d4e5');
// Check remaining recovery codes
$remaining = TwoFactor::getRemainingRecoveryCodes($user);
// Generate device fingerprint (your implementation)
$deviceFingerprint = hash('sha256', $request->ip() . $request->userAgent());
// Trust current device
TwoFactor::trustDevice($user, $deviceFingerprint);
// Check if device is trusted
if (TwoFactor::isDeviceTrusted($user, $deviceFingerprint)) {
// Skip 2FA for trusted device
return redirect('/dashboard');
}
// Remove trusted device
TwoFactor::removeTrustedDevice($user, $deviceFingerprint);
// Get all trusted devices
$trustedDevices = TwoFactor::getTrustedDevices($user);
use WebMonks\Laravel2FA\Facades\TwoFactor;
// Set user's WhatsApp number
TwoFactor::setPhoneNumber($user, '+15551234567');
// Enable WhatsApp 2FA
TwoFactor::enable($user, 'whatsapp');
// Generate and send WhatsApp code
$sent = TwoFactor::generateCode($user, 'whatsapp');
if ($sent) {
return response()->json(['message' => 'WhatsApp code sent successfully']);
}
// Verify WhatsApp code
$isValid = TwoFactor::verifyCode($user, $request->input('code'), 'whatsapp');
// Custom message template
$messageTemplate = 'Your *{app_name}* verification code is: *{code}*\n\nExpires in {expiry_minutes} minutes. š';
// Enable voice call 2FA
TwoFactor::enable($user, 'voice');
// Generate and make voice call
$called = TwoFactor::generateCode($user, 'voice');
if ($called) {
return response()->json(['message' => 'Voice call initiated']);
}
// Verify voice code
$isValid = TwoFactor::verifyCode($user, $request->input('code'), 'voice');
// Supported languages and voices
$languages = ['en-US', 'es-ES', 'fr-FR', 'de-DE', 'it-IT', 'pt-BR', 'ru-RU', 'ja-JP', 'ko-KR', 'zh-CN'];
$voices = ['woman', 'man', 'alice']; // Alice supports more languages
namespace App\Providers\Sms;
use WebMonks\Laravel2FA\Contracts\SmsProvider;
use WebMonks\Laravel2FA\Providers\Sms\AbstractSmsProvider;
class CustomSmsProvider extends AbstractSmsProvider
{
public function send(string $to, string $message, array $options = []): bool
{
// Your custom SMS logic here
$response = Http::post('https://api.yoursms.com/send', [
'api_key' => $this->config['api_key'],
'to' => $to,
'message' => $message,
]);
return $response->successful();
}
public function getName(): string
{
return 'custom';
}
public function getMaxMessageLength(): int
{
return 160;
}
public function getRequiredConfig(): array
{
return ['api_key', 'api_secret'];
}
}
// AppServiceProvider.php
public function register()
{
$this->app->bind('two-factor.sms.custom', function ($app) {
$config = config('two-factor.sms.drivers.custom', []);
return new CustomSmsProvider($config);
});
}
// Generate codes via API
POST /api/two-factor/generate
{
"method": "email" // or "sms", "whatsapp", "voice", "push", "totp"
}
// Verify codes via API
POST /api/two-factor/verify
{
"code": "123456",
"method": "email"
}
// Push notification approval API
POST /api/two-factor/push/approve
{
"challenge_id": "uuid-challenge-id",
"approved": true,
"biometric_used": true
}
// Get user 2FA status
GET /api/two-factor/status
use Illuminate\Support\Facades\Notification;
use WebMonks\Laravel2FA\Notifications\TwoFactorSmsCode;
use WebMonks\Laravel2FA\Facades\TwoFactor;
public function test_email_otp_flow()
{
Mail::fake();
// Enable email 2FA
TwoFactor::enable($this->user, 'email');
// Generate code
TwoFactor::generateCode($this->user, 'email');
// Assert email was sent
Mail::assertSent(TwoFactorCodeMail::class);
// Verify code works
$code = TwoFactor::getLastGeneratedCode($this->user, 'email');
$this->assertTrue(TwoFactor::verifyCode($this->user, $code, 'email'));
}
public function test_sms_otp_flow()
{
Notification::fake();
// Setup SMS
TwoFactor::setPhoneNumber($this->user, '+15551234567');
TwoFactor::enable($this->user, 'sms');
// Generate SMS code
TwoFactor::generateCode($this->user, 'sms');
// Assert SMS notification sent
Notification::assertSentTo($this->user, TwoFactorSmsCode::class);
}
// Multi-layer rate limiting
'rate_limiting' => [
'global' => [
'max_attempts' => 1000, // Global limit
'decay_minutes' => 60,
],
'per_user' => [
'max_attempts' => 10, // Per user limit
'decay_minutes' => 60,
],
'per_ip' => [
'max_attempts' => 50, // Per IP limit
'decay_minutes' => 60,
],
],
// Check Laravel Mail configuration
php artisan config:cache
php artisan queue:work
// Test Laravel Mail directly
Mail::to('[email protected]')->send(new TestMail());
// Check 2FA logs
tail -f storage/logs/laravel.log | grep "2fa"
// Verify SMS provider credentials
php artisan tinker
> config('two-factor.sms.drivers.twilio')
// Test provider connection
> TwoFactor::testSmsProvider('twilio')
// Check phone number format
> PhoneNumberFormatter::format('+1-555-123-4567', 'US')
// Increase time window tolerance
'totp' => [
'window' => 2, // Allow ±2 time periods (±60 seconds)
],
// Check server time synchronization
date_default_timezone_set('UTC');