PHPackages                             mortogo321/laravel-2fa - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. mortogo321/laravel-2fa

ActiveLibrary[Security](/categories/security)

mortogo321/laravel-2fa
======================

A comprehensive Laravel package for Two-Factor Authentication with support for TOTP, WebAuthn/Passkey, SMS, and Email providers

v1.0.0(7mo ago)00MITPHPPHP ^8.1

Since Oct 13Pushed 2mo agoCompare

[ Source](https://github.com/mortogo321/laravel-2fa)[ Packagist](https://packagist.org/packages/mortogo321/laravel-2fa)[ RSS](/packages/mortogo321-laravel-2fa/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (8)Versions (2)Used By (0)

Laravel 2FA Package
===================

[](#laravel-2fa-package)

[![Latest Version on Packagist](https://camo.githubusercontent.com/f2fabf7dfe5893f2948ba5a532f169eed8b7aff34c6abe34896b9460872b6f2e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6f72746f676f3332312f6c61726176656c2d3266612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mortogo321/laravel-2fa)[![Total Downloads](https://camo.githubusercontent.com/c00396f9a934817bbfef0396880e565bf0eec1f571ee079b4728f92d1f121c0a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6f72746f676f3332312f6c61726176656c2d3266612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mortogo321/laravel-2fa)[![License](https://camo.githubusercontent.com/422db9fd40f5831c765cf6530b6750c081b696bd18d904cf89554df98c676277/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e3f7374796c653d666c61742d737175617265)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/ee631d1b3535e8b3a99c9152d465e9db0c74b77d6c84694515f8ebc38cda9aea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c75653f7374796c653d666c61742d737175617265)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/633c4849b1c3c4bdf86d17c2f2e00fe30f260823c500c2ed2b11ee2947047b86/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d25354531302e302d7265643f7374796c653d666c61742d737175617265)](https://laravel.com)

A comprehensive Laravel package for Two-Factor Authentication with support for multiple providers including TOTP (Google Authenticator, Authy), WebAuthn/Passkey, SMS, and Email.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Quick Start](#quick-start)
- [Usage](#usage)
- [Provider-Specific Implementation](#provider-specific-implementation)
- [Recovery Codes](#recovery-codes)
- [API Routes](#api-routes)
- [Middleware](#middleware)
- [Customization](#customization)
- [Events](#events)
- [Security Best Practices](#security-best-practices)
- [Testing](#testing)
- [Troubleshooting](#troubleshooting)
- [FAQ](#faq)
- [Contributing](#contributing)
- [Changelog](#changelog)
- [License](#license)
- [Credits](#credits)
- [Support](#support)

Features
--------

[](#features)

- **Multiple 2FA Providers:**

    - **TOTP (Time-based One-Time Password)**: Works with Google Authenticator, Authy, and other TOTP apps
    - **WebAuthn/Passkey**: Support for hardware security keys and platform authenticators (Touch ID, Face ID, Windows Hello)
    - **SMS**: Send verification codes via SMS
    - **Email**: Send verification codes via email
- **Recovery Codes**: Generate and manage backup recovery codes
- **Flexible Configuration**: Enable/disable providers per user
- **Middleware Protection**: Easy route protection with middleware
- **Rate Limiting**: Built-in brute-force protection
- **Session Management**: Configurable 2FA verification persistence
- **Beautiful UI**: Ready-to-use Blade templates with modern design
- **Extensible Architecture**: Easy to add custom providers

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.0 or higher

Installation
------------

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require mortogo321/laravel-2fa
```

### 2. Publish Configuration

[](#2-publish-configuration)

```
php artisan vendor:publish --tag=two-factor-config
```

This will create a `config/two-factor.php` configuration file.

### 3. Publish Migrations

[](#3-publish-migrations)

```
php artisan vendor:publish --tag=two-factor-migrations
php artisan migrate
```

### 4. (Optional) Publish Views

[](#4-optional-publish-views)

If you want to customize the views:

```
php artisan vendor:publish --tag=two-factor-views
```

Configuration
-------------

[](#configuration)

Open `config/two-factor.php` and configure the providers you want to use:

```
return [
    'providers' => [
        'totp' => [
            'enabled' => true,
            'issuer' => env('APP_NAME', 'Laravel'),
            'qr_code_size' => 200,
            'window' => 1,
        ],
        'webauthn' => [
            'enabled' => true,
            'timeout' => 60000,
            'user_verification' => 'preferred',
            'attestation' => 'none',
        ],
        'sms' => [
            'enabled' => false,
            'driver' => env('TWO_FACTOR_SMS_DRIVER', 'twilio'),
            'from' => env('TWO_FACTOR_SMS_FROM'),
            'code_length' => 6,
            'code_expiry' => 5,
        ],
        'email' => [
            'enabled' => true,
            'from' => [
                'address' => env('MAIL_FROM_ADDRESS'),
                'name' => env('MAIL_FROM_NAME'),
            ],
            'code_length' => 6,
            'code_expiry' => 5,
        ],
    ],

    'recovery' => [
        'enabled' => true,
        'count' => 8,
        'length' => 10,
    ],

    'user_model' => \App\Models\User::class,
];
```

Quick Start
-----------

[](#quick-start)

Get started in 3 simple steps:

```
# 1. Install package
composer require mortogo321/laravel-2fa

# 2. Publish and run migrations
php artisan vendor:publish --tag=two-factor-migrations
php artisan migrate

# 3. Add trait to User model
```

```
// app/Models/User.php
use Mortogo321\Laravel2FA\Traits\HasTwoFactorAuthentication;

class User extends Authenticatable
{
    use HasTwoFactorAuthentication;
}
```

```
// routes/web.php
Route::middleware(['auth', 'two-factor'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});
```

That's it! Your routes are now protected with 2FA. Users can enable it at `/two-factor/settings`.

Usage
-----

[](#usage)

### 1. Add Trait to User Model

[](#1-add-trait-to-user-model)

Add the `HasTwoFactorAuthentication` trait to your User model:

```
use Mortogo321\Laravel2FA\Traits\HasTwoFactorAuthentication;

class User extends Authenticatable
{
    use HasTwoFactorAuthentication;

    // ... rest of your model
}
```

### 2. Protect Routes with Middleware

[](#2-protect-routes-with-middleware)

Apply the `two-factor` middleware to routes that require 2FA verification:

```
// In routes/web.php
Route::middleware(['auth', 'two-factor'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/profile', [ProfileController::class, 'show']);
});
```

### 3. Add 2FA Settings to Your App

[](#3-add-2fa-settings-to-your-app)

Create a link to the 2FA settings page:

```
Two-Factor Authentication
```

Using the Facade
----------------

[](#using-the-facade)

The package provides a convenient facade for programmatic access:

```
use Mortogo321\Laravel2FA\Facades\TwoFactor;

// Check if user has 2FA enabled
if (TwoFactor::isEnabled($user, 'totp')) {
    // TOTP is enabled
}

// Generate credentials for TOTP
$credentials = TwoFactor::generateCredentials($user, 'totp');
// Returns: ['secret' => '...', 'qr_code' => '...', 'qr_code_url' => '...']

// Verify a code
$isValid = TwoFactor::verify($user, 'totp', '123456');

// Enable a provider
TwoFactor::enable($user, 'totp', ['secret' => $secret]);

// Disable a provider
TwoFactor::disable($user, 'totp');

// Get all providers for a user
$providers = TwoFactor::getUserProviders($user);

// Mark user as verified in session
TwoFactor::markAsVerified($user);

// Check if user is verified in current session
if (TwoFactor::isVerified($user)) {
    // User has completed 2FA challenge
}
```

Provider-Specific Implementation
--------------------------------

[](#provider-specific-implementation)

### TOTP (Google Authenticator)

[](#totp-google-authenticator)

1. User enables TOTP from settings page
2. QR code is displayed
3. User scans with authenticator app
4. User enters code to verify
5. TOTP is enabled

**Programmatic Example:**

```
// Generate secret and QR code
$credentials = TwoFactor::generateCredentials($user, 'totp');

// Display QR code to user
echo $credentials['qr_code']; // SVG QR code

// After user scans and enters code, verify and enable
$code = $request->input('code');
if (TwoFactor::verify($user, 'totp', $code)) {
    TwoFactor::enable($user, 'totp', ['secret' => $credentials['secret']]);
}
```

### WebAuthn/Passkey

[](#webauthnpasskey)

WebAuthn requires JavaScript for registration and authentication. Example implementation:

```
// Registration
const response = await fetch('/two-factor/enable/webauthn', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' }
});

const { credentials } = await response.json();
const options = JSON.parse(credentials.options);

// Use WebAuthn API
const credential = await navigator.credentials.create({
    publicKey: options
});

// Send credential back to server for verification
```

### SMS Provider

[](#sms-provider)

To use SMS, you need to implement the SMS sending logic in `SmsProvider::sendSms()`. Example with a notification:

```
// Create a notification
php artisan make:notification TwoFactorCodeNotification

// In the notification
public function via($notifiable)
{
    return ['vonage']; // or 'twilio', etc.
}

public function toVonage($notifiable)
{
    return (new VonageMessage)
        ->content("Your 2FA code is: {$this->code}");
}
```

Then update `SmsProvider.php`:

```
protected function sendSms(Model $user, string $code): void
{
    $user->notify(new TwoFactorCodeNotification($code));
}
```

### Email Provider

[](#email-provider)

Email codes are sent automatically using the included mailable. Make sure your mail configuration is set up in `.env`:

```
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_FROM_ADDRESS="noreply@example.com"
MAIL_FROM_NAME="${APP_NAME}"
```

Recovery Codes
--------------

[](#recovery-codes)

Recovery codes are automatically generated when a user enables their first 2FA method. Users can:

- View their recovery codes at any time
- Regenerate codes (invalidates old ones)
- Use a recovery code in place of a 2FA code

**Using Recovery Codes Programmatically:**

```
use Mortogo321\Laravel2FA\Services\RecoveryCodeService;

$recoveryService = app(RecoveryCodeService::class);

// Generate recovery codes
$codes = $recoveryService->generate($user);
// Returns array of plain-text codes (only time they're visible)

// Verify a recovery code
if ($recoveryService->verify($user, $code)) {
    // Code is valid and will be marked as used
}

// Check if user has unused codes
if ($recoveryService->hasUnusedCodes($user)) {
    $count = $recoveryService->getRemainingCount($user);
}
```

API Routes
----------

[](#api-routes)

The package provides these routes (prefixed with `/two-factor` by default):

MethodURINameDescriptionGET`/two-factor/challenge`two-factor.challengeShow 2FA challenge pagePOST`/two-factor/challenge`two-factor.verifyVerify 2FA codeGET`/two-factor/settings`two-factor.indexShow 2FA settingsPOST`/two-factor/enable/{provider}`two-factor.enableEnable a providerPOST`/two-factor/disable/{provider}`two-factor.disableDisable a providerGET`/two-factor/recovery-codes`two-factor.recovery-codes.showView recovery codesPOST`/two-factor/recovery-codes`two-factor.recovery-codes.regenerateRegenerate codesMiddleware
----------

[](#middleware)

### `two-factor`

[](#two-factor)

Ensures users with 2FA enabled complete the challenge:

```
Route::middleware(['auth', 'two-factor'])->group(function () {
    // Protected routes
});
```

### `two-factor.verified`

[](#two-factorverified)

Ensures user is in the challenge flow:

```
Route::middleware(['auth', 'two-factor.verified'])->group(function () {
    Route::get('/two-factor/challenge', ...);
});
```

Customization
-------------

[](#customization)

### Custom Providers

[](#custom-providers)

Create a custom provider by implementing the `TwoFactorProvider` interface:

```
use Mortogo321\Laravel2FA\Contracts\TwoFactorProvider;

class CustomProvider implements TwoFactorProvider
{
    public function getName(): string
    {
        return 'custom';
    }

    public function generateCredentials(Model $user): array
    {
        // Generate credentials
    }

    public function verify(Model $user, string $code, array $metadata = []): bool
    {
        // Verify code
    }

    // ... implement other methods
}
```

Register your provider in a service provider:

```
use Mortogo321\Laravel2FA\Services\TwoFactorManager;

public function boot()
{
    $manager = app(TwoFactorManager::class);
    $manager->registerProvider('custom', new CustomProvider());
}
```

### Customizing Views

[](#customizing-views)

After publishing the views, you can customize them at:

- `resources/views/vendor/two-factor/challenge.blade.php`
- `resources/views/vendor/two-factor/settings.blade.php`
- `resources/views/vendor/two-factor/recovery-codes.blade.php`
- `resources/views/vendor/two-factor/emails/code.blade.php`

Events
------

[](#events)

The package fires these events (you can create listeners for them):

```
// When 2FA is enabled
event(new TwoFactorEnabled($user, $provider));

// When 2FA is disabled
event(new TwoFactorDisabled($user, $provider));

// When 2FA challenge is passed
event(new TwoFactorVerified($user, $provider));
```

Security Best Practices
-----------------------

[](#security-best-practices)

1. **Always use HTTPS** in production
2. **Enable rate limiting** to prevent brute-force attacks (configured in `config/two-factor.php`)
3. **Store recovery codes securely** - remind users to save them
4. **Use strong encryption** - Laravel's built-in encryption is used for secrets
5. **Monitor failed attempts** - consider logging failed 2FA attempts
6. **Educate users** about phishing and social engineering

Testing
-------

[](#testing)

Run the package tests:

```
composer test
```

Advanced Usage Examples
-----------------------

[](#advanced-usage-examples)

### Example: Custom TOTP Setup Controller

[](#example-custom-totp-setup-controller)

```
