Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fortify Laravel Package

laravel/fortify

Laravel Fortify is a frontend-agnostic authentication backend for Laravel. It provides registration, login, password reset, email verification, and two-factor authentication endpoints and features used by Laravel starter kits, while letting you build your own UI.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require laravel/fortify

Run the publisher to publish Fortify’s configuration and migration:

php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
php artisan migrate
  1. Configure Auth Guard: In config/auth.php, set the default guard to web (or your preferred guard):

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    
  2. Register Fortify: In AppServiceProvider@boot(), register Fortify with your preferred frontend (e.g., Livewire, Inertia, or Blade):

    use Laravel\Fortify\Fortify;
    
    public function boot()
    {
        Fortify::createUsersUsing(app(\Illuminate\Contracts\Auth\Registrar::class));
        Fortify::authenticateUsing(app(\Illuminate\Contracts\Auth\Authenticatable::class));
        Fortify::registerViewHandlers();
        // OR for SPA (e.g., Inertia):
        // Fortify::registerRouteControllers();
    }
    
  3. First Use Case:

    • Blade: Use @auth, @guest, and {{ route('login') }} in your views.
    • SPA (Inertia): Fortify provides API endpoints (e.g., /login, /register) for frontend handling. Example:
      // Inertia.js (SPA)
      router.post('/login', (req) => {
          return axios.post('/sanctum/csrf-cookie');
      });
      

Implementation Patterns

Core Workflows

1. Authentication

  • Login/Logout: Fortify provides LoginController and LogoutController with built-in CSRF protection, throttling, and session handling.

    // Customize login logic (e.g., add 2FA check)
    public function validateLogin(Request $request)
    {
        return parent::validateLogin($request)->safe()->also(function ($request, $user) {
            if ($user->hasEnabledTwoFactorAuthentication()) {
                $request->session()->put('two_factor_intent', true);
                return redirect()->route('two-factor.login');
            }
        });
    }
    
  • Password Reset: Use PasswordResetLinkController and PasswordResetController with email-based or token-based flows:

    // Customize reset logic (e.g., log attempts)
    public function reset(Request $request)
    {
        $response = parent::reset($request);
        event(new PasswordResetAttempted($request->email));
        return $response;
    }
    

2. Two-Factor Authentication (2FA)

  • Enable/Disable: Use EnableTwoFactorAuthentication and DisableTwoFactorAuthentication actions:
    use Laravel\Fortify\Actions\EnableTwoFactorAuthentication;
    
    public function enableTwoFactor(Request $request)
    {
        return (new EnableTwoFactorAuthentication())($request)->response();
    }
    
  • Recovery Codes: Generate/revoke codes via TwoFactorRecoveryCodeController:
    // Generate new codes
    $user->generateTwoFactorRecoveryCodes();
    

3. Profile Management

  • Update Profile/Email/Password: Extend UpdateUserProfileInformation and UpdateUserPassword actions:
    use Laravel\Fortify\Actions\UpdateUserPassword;
    
    public function updatePassword(Request $request)
    {
        return (new UpdateUserPassword())($request)->response();
    }
    

4. Frontend Agnostic Patterns

  • Blade Views: Fortify includes Blade views for login, registration, and 2FA. Override them in resources/views/vendor/fortify/.
  • SPA (Inertia/Vue/React): Fortify routes are API-first. Example Inertia setup:
    // routes/web.js (Inertia)
    import { createInertiaApp } from '@inertiajs/inertia-react';
    createInertiaApp({
        resolve: (name) => require(`./Pages/${name}.jsx`),
        setup({ el, App, props }) {
            return createApp({ render: () => h(App, props) }).mount(el);
        },
    });
    
    Use Fortify’s API endpoints (e.g., POST /login) in your frontend.

5. Custom Guards

  • Database Guard: Fortify works out-of-the-box with Laravel’s default web guard. For custom guards (e.g., api), configure:

    Fortify::authenticateUsing(app(\App\Services\CustomAuthenticatable::class));
    
  • Sanctum for SPAs: Ensure Sanctum is installed and configured:

    composer require laravel/sanctum
    php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
    

    Fortify integrates with Sanctum automatically for SPA sessions.


Integration Tips

  1. Middleware: Use Fortify’s built-in middleware (e.g., EnsureEmailIsVerified, RedirectIfTwoFactorAuthenticatable) in routes:

    Route::middleware(['auth', 'verified'])->group(function () {
        // Protected routes
    });
    
  2. Events: Listen to Fortify events (e.g., TwoFactorAuthenticationEnabled) for custom logic:

    event(new TwoFactorAuthenticationEnabled($user));
    
  3. Testing: Use Fortify’s test helpers:

    use Laravel\Fortify\Testing\Concerns\InteractsWithFortify;
    
    public function test_login()
    {
        $this->actingAs(User::factory()->create())
             ->post('/logout')
             ->assertRedirect('/');
    }
    
  4. Passkeys (v1.37+): Enable passkey authentication:

    Fortify::enablePasskeys();
    

    Update your frontend to support WebAuthn (e.g., using @simplewebauthn/browser).


Gotchas and Tips

Pitfalls

  1. Route Conflicts:

    • Fortify registers routes under /sanctum for SPAs and /login for Blade. Ensure no conflicts with existing routes.
    • Fix: Rename routes in FortifyServiceProvider or use route middleware to restrict access.
  2. Session Handling:

    • Fortify regenerates sessions on login/register by default. Disable with:
      Fortify::regenerateSessionOnLogin(false);
      
  3. 2FA State Management:

    • The InteractsWithTwoFactorState trait manages 2FA state across requests. Clear it manually if needed:
      $request->session()->forget('two_factor_intent');
      
  4. Password Reset Tokens:

    • Tokens expire after 60 minutes by default. Customize in config/fortify.php:
      'password_reset' => [
          'expire_after' => 60, // minutes
      ],
      
  5. SPA Sanctum Issues:

    • Ensure Sanctum’s middleware is registered before Fortify’s:
      $router->middlewareGroup('web', [
          \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
          // Other middleware...
      ]);
      
  6. Passkey Browser Support:

    • Passkeys require modern browsers (Chrome 89+, Edge 89+, Safari 15.4+). Test thoroughly.

Debugging

  1. Throttling:

    • Fortify throttles login/registration attempts. Check config/fortify.php for limits:
      'throttle' => [
          'max_attempts' => 5,
          'decay_minutes' => 1,
      ],
      
  2. Email Verification:

    • Debug failed verifications with:
      $user->hasVerifiedEmail(); // Check status
      $user->markEmailAsVerified(); // Manually verify
      
  3. 2FA QR Codes:

    • Ensure pragmarx/google2fa is installed and the two_factor_secret column exists in your users table.
  4. Route Debugging:

    • List Fortify routes with:
      php artisan route:list | grep fortify
      

Extension Points

  1. Custom Actions: Extend Fortify’s actions (e.g., CreateNewUser). Example:

    use Laravel\Fortify\Actions\CreateNewUser;
    
    class CustomCreateNewUser extends CreateNewUser
    {
        public function create(array $data)
        {
            $user = parent::create($data);
            // Custom logic (e.g., assign role)
            return $user;
        }
    }
    

    Register in AppServiceProvider:

    Fortify::createUsersUsing(app(CustomCreateNewUser::class));
    
  2. Custom Views: Override Fortify’s Blade views in `resources/views/vendor

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony