Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

TwoFactor

> 后端框架
Open source

Two-Factor Authentication for all your users out-of-the-box.

341 stars0 likes0 views
WebsiteGitHub

About

Two-Factor Authentication for all your users out-of-the-box.

Two Factor

On-premises Two-Factor Authentication for all your users out of the box.

php
use Illuminate\Http\Request;
use Laragear\TwoFactor\Facades\Auth2FA;

public function login(Request $request)
{
    $attempt = Auth2FA::attempt($request->only('email', 'password'));
    
    if ($attempt) {
        return 'You are logged in!';
    }
    
    return 'Hey, you should make an account!';
}

This package enables TOTP authentication using 6 digits codes. No need for external APIs.

[!TIP]

Want to authenticate users with Passkeys? Check out Laragear WebAuthn.

Become a sponsor

Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can spread the word on social media!

Requirements

  • PHP 8.3 or later
  • Laravel 12 or later

Installation

Fire up Composer and require this package in your project.

bash
composer require laragear/two-factor

That's it.

How this works

This package adds a Contract to detect if a user, after the credentials are deemed valid, should use Two-Factor Authentication as a second layer of authentication.

It includes a custom view and a helper to handle the Two-Factor authentication itself during login attempts.

Works without middleware or new guards, but you can go full manual if you want.

Set up

  1. First, install the migration, translations, views and config into your application, with the two-factor:install Artisan command.
bash
php artisan two-factor:install

[!TIP]

You can edit the migration by adding new columns before migrating, and also change the table name.

After that, you may migrate your table like always through the Artisan command.

bash
php artisan migrate
  1. Add the TwoFactorAuthenticatable contract and the TwoFactorAuthentication trait to the User model, or any other model you want to make Two-Factor Authentication available.
…

php use Illuminate\Http\Request;

public function prepareTwoFactor(Request $request) { $secret = $request->user()->createTwoFactorAuth();

return view('user.2fa', [
    'qr_code' => $secret->toQr(),     // As QR Code
    'uri'     => $secret->toUri(),    // As "otpauth://" URI.
    'string'  => $secret->toString(), // As a string
]);

}


> [!TIP]
> 
> When you use `createTwoFactorAuth()` on someone with Two-Factor Authentication already enabled, the previous data becomes permanently invalid. This ensures a User **never** has two Shared Secrets enabled at any given time.

Then, the User must confirm the Shared Secret with a Code generated by their Authenticator app. The `confirmTwoFactorAuth()` method will automatically enable it if the code is valid.

```php
use Illuminate\Http\Request;

public function confirmTwoFactor(Request $request)
{
    $request->validate([
        'code' => 'required|numeric'
    ]);
    
    $activated = $request->user()->confirmTwoFactorAuth($request->code);
    
    // ...
}

If the User doesn't issue the correct Code, the method will return false. You can tell the User to double-check its device's timezone, or create another Shared Secret with createTwoFactorAuth().

Recovery Codes

Recovery Codes are automatically generated each time the Two-Factor Authentication is enabled. By default, a Collection of ten one-use 8-characters codes are created.

You can show them using getRecoveryCodes().

php
use Illuminate\Http\Request;

public function confirmTwoFactor(Request $request)
{
    if ($request->user()->confirmTwoFactorAuth($request->code)) {
        return $request->user()->getRecoveryCodes();
    }
    
    return 'Try again!';
}

You're free on how to show these codes to the User, but ensure you show them at least one time after a successfully enabling Two-Factor Authentication, and ask him to print them somewhere.

[!TIP]

These Recovery Codes are handled automatically when the User sends it instead of a TOTP code. If it's a recovery code, the package will use and mark it as invalid, so it can't be used again.

The User can generate a fresh batch of codes using generateRecoveryCodes(), which replaces the previous batch.

php
use Illuminate\Http\Request;

public function showRecoveryCodes(Request $request)
{
    return $request->user()->generateRecoveryCodes();
}

…

php
use Laragear\TwoFactor\Models\TwoFactorAuthentication;
use MyRandomGenerator;

$generator = function ($length, $iteration, $amount) {
    return MyRandomGenerator::random($length)->make();
}

TwoFactorAuthentication::generateRecoveryCodesUsing($generator);

…

php
use Laragear\TwoFactor\Facades\Auth2FA;
use Illuminate\Http\Request;

public function login(Request $request)
{
    // If the user is trying for the first time, ensure both email and the password are
    // required to log in. If it's not, then he would issue its 2FA code. This ensures
    // the credentials are not required again when is just issuing his 2FA code alone.
    if ($request->isNotFilled('2fa_code')) {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|string'
        ]);
    }
    
    $attempt = Auth2FA::attempt($request->only('email', 'password'), $request->filled('remember'));
    
    if ($attempt) {
        return redirect()->home();
    }
    
    return back()->withErrors(['email' => 'There is no existing user for these credentials']);
}

…

php
use Laragear\TwoFactor\Facades\Auth2FA;

Auth2FA::message('You need 2FA set up to access this area')
    ->redirect('/auth/2fa-required')
    ->input('2fa-code')
    ->attempt($request->only('email', 'password'), $request->filled('remember'));

[!NOTE]

If you're using scaffolding packages like Laravel UI, Breeze, Fortify, JetStream, Inertia or Livewire, to name some, you may require to change or alter their proper authentication flow. Refer to their documentation for further details.

Alternatively, you may use Auth::attemptWhen() with TwoFactor helper methods, which returns a callback to check if the user needs a 2FA Code before proceeding using TwoFactor::hasCode().

php
use Illuminate\Support\Facades\Auth;
use Laragear\TwoFactor\TwoFactor;

$attempt = Auth::attemptWhen(
    [/* Credentials... */], TwoFactor::hasCode(), $request->filled('remember')
);

You can use the hasCodeOrFails() method that does the same, but throws a validation exception, which is handled gracefully by the framework. It even accepts a custom message in case of failure, otherwise a default translation line will be used.

Determining Safe Device bypass

When the user is under a safe device, which is determined by cookie, no 2FA code will be required to log in. To check if this was the case on the current request, use the wasTwoFactorBypassedBySafeDevice() method on the user.

php
use Illuminate\Http\Request;

public function changeServerSetting(Request $request)
{
    if ($request->user()->wasTwoFactorBypassedBySafeDevice()) {
        // Do something ...
    }
    
    // ...
}

Deactivation

You can deactivate Two-Factor Authentication for a given User using the disableTwoFactorAuth() method. This will automatically invalidate the authentication data, allowing the User to log in with just his credentials.

php
public function disableTwoFactorAuth(Request $request)
{
    $request->user()->disableTwoFactorAuth();
    
    return 'Two-Factor Authentication has been disabled!';
}

…

php
Route::get('system/settings', function () {
    // ...
})->middleware('2fa.enabled');

You can implement the view easily with the one included in this package, optionally with a URL to point the user to enable 2FA:

php
use Illuminate\Support\Facades\Route;

Route::view('2fa-required', 'two-factor::notice', [
    'url' => url('settings/2fa')
])->name('2fa.notice');

Confirm 2FA

Much like the password.confirm middleware, you can also ask the user to confirm entering a route by issuing a 2FA Code with the 2fa.confirm middleware.

php
Route::get('api/token', function () {
    // ...
})->middleware('2fa.confirm');

Route::post('api/token/delete', function () {
    // ...
})->middleware('2fa.confirm');

The middleware will redirect the user to the named route 2fa.confirm by default, but you can change it in the first parameter. To implement the receiving routes, TwoFactor comes with the Confirm2FACodeController and a view you can use for a quick start.

php
use Illuminate\Support\Facades\Route;
use Laragear\TwoFactor\Http\Controllers\ConfirmTwoFactorCodeController;

Route::get('2fa-confirm', [ConfirmTwoFactorCodeController::class, 'form'])
    ->name('2fa.confirm');

Route::post('2fa-confirm', [ConfirmTwoFactorCodeController::class, 'confirm']);

Since a user without 2FA enabled won't be asked for a code, you can combine the middleware with 2fa.require to ensure confirming is mandatory for users without 2FA enabled.

php
use Illuminate\Support\Facades\Route;

Route::get('api/token', function () {
    // ...
})->middleware('2fa.require', '2fa.confirm');

Force confirmation

When user confirm with their TOTP code, the middleware will remember the confirmation for a set amount of time.

You may always force a confirmation, even if the user already confirmed, setting the first or second parameter as "force" or "true".

php
use Illuminate\Support\Facades\Route;

Route::get('api/token', function () {
    // ...
})->middleware('2fa.require', '2fa.confirm:force');

Route::get('api/important-token', function () {
    // ...
})->middleware('2fa.require', '2fa.confirm:my-redirect-route-name,true');

Throttling Middleware

This library includes a global throttling middleware. It will trigger a TOTP confirmation once a number of Requests done to the application exceed a default threshold.

To enable the global middleware, set the OTP_THROTTLE environment variable to true.

dotenv
OTP_THROTTLE

Alternatively, you can enable it globally and also set the threshold using {tries},{decay} notation. For example, to change the threshold to a maximum of 3 requests each 15 seconds.

dotenv
OTP_THROTTLE=3,15

…

php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Laragear\TwoFactor\Http\Middleware\ThrottleWithTwoFactor;

return Application::configure()
    ->booted(function () {
        ThrottleWithTwoFactor::$key = function (Request $request) {
            return $request->ip() . '|' . $request->user()->getKey(); 
        }
    })
    ->create();

Determining if the request should be throttled

You may programmatically throttle requests by setting a callback in the $shouldThrottle static property of the Laragear\TwoFactor\Http\Middleware\ThrottleWithTwoFactor class, in your bootstrap/app.php file.

php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Laragear\TwoFactor\Http\Middleware\ThrottleWithTwoFactor;

return Application::configure()
    ->booted(function () {
        ThrottleWithTwoFactor::$shouldThrottle = function (Request $request) {
            return $request->user()->isNotVip(); 
        }
    })
    ->create();

Inside the function, you can use the method clearAttempts() of the middleware instance present as a second parameter in the callback to clear the attempts of the given request.

php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Laragear\TwoFactor\Http\Middleware\ThrottleWithTwoFactor;

return Application::configure()
    ->booted(function () {
        ThrottleWithTwoFactor::$shouldThrottle = function (Request $request, ThrottleWithTwoFactor $instance) {
            if ($request->user()->impersontedByAdmin()) {

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHP2fa2factorauthenticationlaravel

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架