Laravel Fortify

repository·1.x·Indexed 23 days ago

https://github.com/laravel/fortify

A frontend-agnostic backend authentication engine for Laravel. It provides the underlying logic and routing for essential features including registration, login, two-factor authentication (2FA), WebAuthn passkeys, email verification, and password resets without forcing a specific UI implementation.

Tokens
4.6K
Snippets
2
Records
27
Agent score
82%

What's inside Laravel Fortify

  1. What is Laravel Fortify

    1.x

    Laravel Fortify is a frontend-agnostic authentication backend designed for Laravel applications. It provides the underlying logic for essential authentication features including:

    • Registration
    • Authentication
    • Two-factor authentication (2FA)

    Because it is frontend-agnostic, it handles the backend logic and routing without forcing a specific UI, making it suitable for use with various Laravel Starter Kits or custom frontend implementations.

  2. Customize Authentication Logic and Responses

    1.x

    Fortify provides several ways to override default behavior:

    Custom User Retrieval and Pipeline

    • Use Fortify::authenticateUsing() to customize how a user is retrieved during authentication.
    • Use Fortify::authenticateThrough() to customize the authentication pipeline.

    Customizing Responses

    • To change where users are redirected after login or logout, override the corresponding response contracts (e.g., LoginResponse, LogoutResponse) in your AppServiceProvider.

    Customizing Registration

    • To change how users are created or what validation rules are applied during signup, modify the logic in app/Actions/Fortify/CreateNewUser.php.
  3. Set up SPA Authentication

    1.x

    To use Fortify as a headless backend for a Single Page Application (SPA):

    1. In config/fortify.php, set 'views' => false. This causes Fortify to return JSON responses instead of redirects.
    2. Install and configure Laravel Sanctum for session-based authentication.
    3. Ensure config/fortify.php is configured to use the 'web' guard.
    4. Configure proper CSRF token handling in your SPA.
    5. Note on 2FA in SPA mode: If a user attempts to log in while 2FA is enabled, Fortify will return a JSON response indicating a challenge is required:
    {
        "two_factor": true
    }
  4. Enable Two Factor Brute Force Protection

    1.x

    To protect against brute force attacks on the two-factor authentication form (introduced in Fortify 1.7.3), you must configure rate limiting for the two-factor feature. This involves two steps: enabling the limiter in the Fortify configuration and defining the limiter logic in your FortifyServiceProvider.

    // 1. In config/fortify.php
    'limiters' => [
        'login' => 'login',
        'two-factor' => 'two-factor',
    ],
    
    // 2. In app/Providers/FortifyServiceProvider.php
    RateLimiter::for('two-factor', function (Request $request) {
        return Limit::perMinute(5)->by($request->session()->get('login.id'));
    });
  5. Set up Two-Factor Authentication (2FA)

    1.x

    To implement Two-Factor Authentication with TOTP and recovery codes, follow these steps:

    1. Add the TwoFactorAuthenticatable trait to your User model.
    2. Enable the feature in config/fortify.php using Features::twoFactorAuthentication().
    3. Ensure the necessary database columns exist. If the *_add_two_factor_columns_to_users_table.php migration is missing, publish it using: php artisan vendor:publish --tag=fortify-migrations and then run your migrations.
    4. Set up view callbacks in your FortifyServiceProvider to handle the 2FA UI.
    5. Create a management UI for users to enable/disable 2FA and view recovery codes.
    6. Test the QR code generation and recovery code flows.
  6. Set up Email Verification

    1.x

    To require users to verify their email addresses:

    1. Enable the emailVerification feature in config/fortify.php.
    2. Implement the MustVerifyEmail interface on your User model.
    3. Set up the verifyEmailView callback in your FortifyServiceProvider to render the verification notice.
    4. Protect your routes using the verified middleware.
    5. Test the verification email delivery and link flow.
  7. Set up Passkeys (WebAuthn)

    1.x

    To implement passwordless authentication via Passkeys:

    1. Add the PasskeyAuthenticatable trait to your User model and ensure it implements the PasskeyUser interface.
    2. Enable the feature in config/fortify.php using Features::passkeys().
    3. Publish and run migrations if the passkeys table is missing: php artisan vendor:publish --tag=fortify-migrations.
    4. Configure WebAuthn settings in config/fortify.php (e.g., relying_party_id, allowed_origins, user_handle_secret, and timeout) if the defaults are insufficient.
    5. Build the frontend UI using the @laravel/passkeys package for registration, login, confirmation, and deletion flows.
  8. Set up Password Reset

    1.x

    To enable password resets via email:

    1. Enable the resetPasswords feature in config/fortify.php.
    2. Set up the requestPasswordResetLinkView callback in FortifyServiceProvider to show the request form.
    3. Set up the resetPasswordView callback in FortifyServiceProvider to show the actual reset form.
    4. If you are disabling Fortify's built-in views, ensure you define a named route password.reset.
    5. Test the full flow from requesting a link to resetting the password.
  9. Customize login and logout responses

    1.x

    Fortify uses contract-based responses for authentication flows, allowing you to swap the default behavior (like redirection) with your own implementation.

    To change what happens after a successful login or a logout, you should bind your own implementation of the following contracts in your AppServiceProvider:

    • Laravel\Fortify\Contracts\LoginResponse: Triggered after a successful authentication.
    • Laravel\Fortify\Contracts\LogoutResponse: Triggered after a session is destroyed.
    • Laravel\Fortify\Contracts\LoginViewResponse: Triggered when the login form view is requested.
  10. Configure Fortify features

    1.x

    Fortify features are managed via the features array in config/fortify.php. You can enable or disable specific authentication capabilities using the Features class constants.

    Available features include:

    • Features::registration(): Enables user registration.
    • Features::resetPasswords(): Enables password reset via email.
    • Features::emailVerification(): Enables email verification (requires the User model to implement MustVerifyEmail).
    • Features::updateProfileInformation(): Enables profile updates.
    • Features::updatePasswords(): Enables password changes.
    • Features::twoFactorAuthentication(): Enables 2FA with QR codes and recovery codes.
    • Features::passkeys(): Enables passwordless authentication with WebAuthn passkeys.
  11. Install Fortify scaffolding via fortify:install

    1.x

    Run the fortify:install Artisan command to set up the necessary Fortify resources in your Laravel application. This command performs two main actions:

    1. Publishes Fortify resources: It executes vendor:publish using the Laravel\Fortify\FortifyServiceProvider to bring configuration and other assets into your application.
    2. Registers the Service Provider: It attempts to register App\Providers\FortifyServiceProvider into your application's bootstrap configuration so that Fortify's features are active.
  12. Configure the two-factor authentication verification window

    1.x

    The TwoFactorAuthenticationProvider uses a configuration value to determine the allowed time window for verifying two-factor authentication codes. This window helps account for clock drift between the server and the user's device.

    You can set this value in your configuration using the fortify-options.two-factor-authentication.window key. The value should be an integer representing the number of time steps (usually 30-second intervals) allowed.