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 the core endpoints and logic for registration, login, password reset, email verification, and two-factor authentication used by Laravel starter kits.

View on GitHub
Deep Wiki
Context7
## Getting Started

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

Run the Fortify publisher to generate configuration and migrations:

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

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    
  2. First Use Case:

    • SPA/API Authentication: Register routes in routes/api.php:

      use Laravel\Fortify\Features;
      use Laravel\Fortify\Http\Controllers;
      
      Features::registerRoutes();
      

      Ensure Sanctum is installed and configured for token-based auth:

      composer require laravel/sanctum
      php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
      php artisan migrate
      
    • Traditional Blade Authentication: Register routes in routes/web.php:

      use Laravel\Fortify\Http\Controllers;
      
      Route::get('/dashboard', [Controllers\AuthenticatedSessionController::class, 'dashboard'])->middleware('auth');
      Features::registerRoutes();
      

Key Files to Review

  • config/fortify.php: Customize features (e.g., email verification, 2FA, password reset).
  • app/Providers/FortifyServiceProvider.php: Extend or override default behaviors.
  • routes/web.php or routes/api.php: Register Fortify routes.

Implementation Patterns

Core Workflows

1. User Registration & Authentication

  • Registration: Fortify handles registration via CreateNewUser controller. Customize validation in FortifyServiceProvider:

    Fortify::createUsersUsing(function ($data) {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    });
    

    Trigger registration via:

    POST /register
    
  • Login: Use AttemptToAuthenticate controller. For SPA/APIs, return a Sanctum token:

    public function store(Request $request)
    {
        $request->authenticate();
        $request->session()->regenerate();
        return response()->json(['user' => $request->user(), 'token' => $request->user()->createToken('api-token')->plainTextToken]);
    }
    

2. Password Reset & Email Verification

  • Password Reset: Configure email templates in resources/views/vendor/fortify/. Trigger reset via:

    POST /forgot-password
    POST /reset-password
    

    Customize reset logic:

    Fortify::resetPasswordsUsing(function ($user, $password) {
        $user->forceFill(['password' => Hash::make($password)])->save();
    });
    
  • Email Verification: Enable in config/fortify.php:

    'features' => [
        Features::emailVerification(),
    ],
    

    Verify via:

    POST /email/verification-send
    GET /email/verify?signed={signature}
    

3. Two-Factor Authentication (2FA)

  • Enable 2FA in config/fortify.php:
    'features' => [
        Features::twoFactorAuthentication(),
    ],
    
    Trigger 2FA setup:
    POST /user/two-factor-authentication
    
    Verify codes:
    POST /user/two-factor-authentication/verify-code
    

4. Profile Updates

  • Update user profile via UpdateUserProfileInformation:
    PUT /user/profile-information
    
    Update password via UpdateUserPassword:
    PUT /user/password
    

Integration Tips

Frontend Agnostic Design

  • SPA/APIs: Use Sanctum for token-based auth. Fortify’s AttemptToAuthenticate returns a JSON response with a token by default.

    // In FortifyServiceProvider.php
    Fortify::authenticateUsing(function (Request $request) {
        $user = User::where('email', $request->email)->first();
        if ($user && Hash::check($request->password, $user->password)) {
            return $user;
        }
        return null;
    });
    
  • Blade Views: Fortify includes Blade views for login, registration, and password reset. Customize them in resources/views/vendor/fortify/.

Middleware & Policies

  • Protect routes with auth middleware:
    Route::middleware(['auth'])->group(function () {
        Route::get('/dashboard', function () { ... });
    });
    
  • Use Fortify::authenticate() in custom middleware to validate sessions.

Events & Listeners

  • Listen to Fortify events (e.g., TwoFactorAuthenticated) in EventServiceProvider:
    protected $listen = [
        \Laravel\Fortify\Events\TwoFactorAuthenticated::class => [
            \App\Listeners\LogTwoFactorAuth::class,
        ],
    ];
    

Customizing Responses

  • Override default responses in FortifyServiceProvider:
    Fortify::authenticated(function (Request $request, User $user) {
        return response()->json(['message' => 'Authenticated successfully']);
    });
    

Gotchas and Tips

Common Pitfalls

1. Route Conflicts

  • Issue: Fortify registers routes with names like login, register, etc., which may conflict with existing routes. Fix: Rename routes in FortifyServiceProvider:
    Fortify::loginView(function () {
        return route('custom.login');
    });
    

2. Session Handling in APIs

  • Issue: Fortify uses sessions by default, which may not work with APIs. Fix: Disable sessions for API routes and use Sanctum:
    // In FortifyServiceProvider.php
    Fortify::ignoreRoutes();
    Fortify::createApiRoutes();
    

3. 2FA State Management

  • Issue: 2FA state (e.g., two_factor_confirmed_at) may not persist across requests. Fix: Use InteractsWithTwoFactorState trait or manually manage state in sessions:
    use Laravel\Fortify\Features\TwoFactorAuthentication\InteractsWithTwoFactorState;
    

4. Password Hashing Mismatches

  • Issue: Passwords hashed with different algorithms (e.g., bcrypt vs. argon2) may fail authentication. Fix: Ensure consistent hashing in CreateNewUser and ResetPassword:
    Fortify::createUsersUsing(function ($data) {
        return User::create([
            'password' => Hash::make($data['password']), // Use same algorithm
        ]);
    });
    

5. Email Verification Tokens

  • Issue: Verification tokens may expire or be invalid. Fix: Extend token lifetime in VerifyEmail:
    Fortify::verifyEmailUsing(function (Request $request) {
        $request->user()->markEmailAsVerified();
        return redirect()->intended('/dashboard');
    });
    

Debugging Tips

1. Logging Authentication Events

  • Enable Laravel logging for Fortify events:
    // In AppServiceProvider
    Fortify::authenticated(function (Request $request, User $user) {
        \Log::info('User authenticated', ['user' => $user->id]);
    });
    

2. Testing 2FA

  • Manually trigger 2FA events for testing:
    $user = User::find(1);
    $user->forceFill(['two_factor_secret' => 'SECRET'])->save();
    event(new \Laravel\Fortify\Events\TwoFactorAuthenticated($user));
    

3. Inspecting Requests

  • Dump Fortify requests in middleware:
    public function handle($request, Closure $next) {
        \Log::info('Fortify Request', ['input' => $request->all()]);
        return $next($request);
    }
    

Configuration Quirks

1. Custom User Models

  • Issue: Fortify assumes a User model. Custom models require explicit configuration:
    Fortify::userModel(\App\Models\CustomUser::class);
    

2. Guard-Specific Settings

  • Issue: Fortify defaults to the web guard. For custom guards (e.g., api), specify:
    Fortify::authGuard('api');
    

3. Rate Limiting

  • Issue: Rate limiting may block legitimate requests. Fix: Adjust thrott
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport