Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 67 ยท Authentication and Authorization

Fortify, Email Verification and Password Reset

How Laravel Fortify provides the authentication backend: email verification, password reset links, password confirmation, customizing actions, and 2FA and passkeys.

Logging in is only the start of account management. Users forget passwords, mistype email addresses, change their details and sometimes want stronger protection than a password alone. Each of those flows has security traps: reset links that never expire, verification links that can be forged, endless requests that flood someone's inbox. Laravel Fortify is the official package that implements them correctly once, so you don't rebuild them in every project.

Fortify is headless: it registers the routes and controllers but has no views of its own. You tell it which pages to show, and it handles the forms they submit. The starter kits (Authentication Overview and Starter Kits) are built this way, so what you read here explains the generated code in your own project, and it is where you go to customize it.

What Fortify gives you

Fortify is switched on feature by feature in config/fortify.php:

PHP
use Laravel\Fortify\Features;

'features' => [
    Features::registration(),
    Features::resetPasswords(),
    Features::emailVerification(),
    Features::updateProfileInformation(),
    Features::updatePasswords(),
    Features::twoFactorAuthentication([
        'confirm' => true,
        'confirmPassword' => true,
    ]),
],

Each entry adds routes, controllers and the logic behind them. Only the features you list exist, so an application that doesn't allow self-registration simply leaves that line out. The exact feature list and options differ a little between Fortify and starter kit versions, so check config/fortify.php in your project.

Fortify supplies endpoints; your application supplies the screens. In a service provider (a Fortify-based starter kit has one called FortifyServiceProvider) you point Fortify at your views:

PHP
use Laravel\Fortify\Fortify;

public function boot(): void
{
    Fortify::loginView(fn () => view('auth.login'));
    Fortify::registerView(fn () => view('auth.register'));
    Fortify::requestPasswordResetLinkView(fn () => view('auth.forgot-password'));
    Fortify::resetPasswordView(fn ($request) => view('auth.reset-password', ['request' => $request]));
    Fortify::verifyEmailView(fn () => view('auth.verify-email'));
    Fortify::confirmPasswordView(fn () => view('auth.confirm-password'));
}

Service providers and where this code lives are covered in Service Providers, Facades and Contracts. Run php artisan route:list to see every route Fortify added.

Customizing the actions

The business logic is not hidden in the package. Fortify delegates to small action classes that live in your own app/Actions/Fortify directory, one per job:

PHP
namespace App\Actions\Fortify;

use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;

class CreateNewUser implements CreatesNewUsers
{
    public function create(array $input): User
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:12', 'confirmed'],
        ])->validate();

        return User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => $input['password'],
        ]);
    }
}

Want a username field, an invitation code or a terms checkbox? Edit this file. Fortify finds the class through Fortify::createUsersUsing(CreateNewUser::class), with matching hooks for ResetUserPassword, UpdateUserProfileInformation and UpdateUserPassword. The class implements an interface (a contract) so you can swap it freely, and the controllers around it, with throttling, redirects and session handling, remain Fortify's concern.

You can also change how users are looked up at login, for example allowing a username instead of an email, with Fortify::authenticateUsing(...), and the login throttle is a named rate limiter you can tune. Login itself behaves as described in Registering, Logging In and Out.

flowchart LR
    R["Request<br/>POST /register"] --> F["Fortify controller<br/>(vendor)"]
    F --> A["CreateNewUser action<br/>(your app)"]
    A --> U["User model"]
    F --> V["Your view<br/>or redirect"]

Fortify owns the routes and controllers; the action and the views are yours to change.

Email verification

Verification proves that a user controls the address they typed. It protects you from typos, fake sign-ups and people registering with somebody else's email.

Your User model opts in with an interface:

PHP
use Illuminate\Contracts\Auth\MustVerifyEmail;

class User extends Authenticatable implements MustVerifyEmail
{
    // ...
}

With Features::emailVerification() enabled, registration sends a notification containing a signed URL. When the user clicks it, Fortify checks the signature, sets email_verified_at and redirects. You then require verification where it matters by adding the verified middleware, which sends unverified users to the "please verify" page:

PHP
Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/billing', BillingController::class);
});

Two small flows round it out: the verify notice page tells the user to check their inbox, and a "resend" form posts to a throttled route that mails the link again. In local development the mail goes to the log (or to a tool like Mailpit that Herd provides), covered in Sending Mail. Note that verification is optional unless you add the middleware, so a site may let people in immediately and gate only sensitive pages.

Signed URLs, and a stand-in

Why can't someone guess /email/verify/42/abc for another user? Because the link carries a signature: an HMAC of the URL, computed with the application's secret key (APP_KEY), plus an optional expiry timestamp. Changing the id, the hash or the expiry changes the HMAC, so the check fails. Laravel exposes this as URL::temporarySignedRoute() for creating, and the signed middleware (or $request->hasValidSignature()) for checking.

The stand-in below builds and validates such URLs with hash_hmac. Real Laravel signs the full URL including host, and your secret key never leaves the server. The clock is passed in, so the output is stable.

PHP A signed, expiring verification link

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The valid link works until it expires, and the two tampered copies fail even though they look almost identical. Laravel's real verification link also contains a hash derived from the user's email, so the link stops working if the address changes first.

Password reset

A forgotten-password flow must work for people locked out of their accounts, yet must not become a way to take over accounts. Laravel's password broker handles this in two steps:

  1. The user submits their email. The broker creates a random token, stores a hash of it in the password_reset_tokens table, and sends the plain token inside a link. The table is configured under passwords in config/auth.php: tokens expire after expire minutes (60 by default) and a user can request another link only after throttle seconds.
  2. The user opens the link, picks a new password, and the broker verifies the token, runs your reset callback, and deletes the token.

Fortify does this for you. When you do it by hand, the facade Password is the API:

PHP
use Illuminate\Support\Facades\Password;

$status = Password::sendResetLink($request->only('email'));

return $status === Password::RESET_LINK_SENT
    ? back()->with('status', __($status))
    : back()->withErrors(['email' => __($status)]);

// Later, on the reset form's POST:
$status = Password::reset(
    $request->only('email', 'password', 'password_confirmation', 'token'),
    function (User $user, string $password) {
        $user->forceFill(['password' => $password])->setRememberToken(Str::random(60));
        $user->save();
    }
);

Two design decisions deserve attention. The stored value is a hash, just like a password, so someone who reads the database can't use the tokens. And the response to "send reset link" should not reveal whether an address is registered; the throttle also stops attackers using your form to spam a person's inbox.

The stand-in reproduces the broker's rules: hashed storage, expiry, one-time use and a throttle. It uses password_hash with a low cost (4) only to keep the demonstration fast; real code uses your configured hasher.

PHP A password reset broker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The wrong guess fails, the right token works exactly once, and an old link is useless after the expiry window. Laravel's broker also invalidates the token when it deletes the row after a successful reset.

Password confirmation

Some actions deserve a second check even for a logged-in user, such as deleting an account, changing security settings or viewing recovery codes. The password.confirm middleware redirects to a "confirm your password" screen, stores a timestamp in the session on success and lets the user through until it expires:

PHP
Route::post('/settings/delete-account', [AccountController::class, 'destroy'])
    ->middleware(['auth', 'password.confirm']);

The window is set by password_timeout in config/auth.php (3 hours by default, in seconds). Shorten it for sensitive screens or use a dedicated confirmation. Fortify provides the confirmation route and the view hook confirmPasswordView.

Two-factor authentication and passkeys

A password alone can be phished or reused. Two-factor authentication (2FA) adds a second proof: with Fortify's twoFactorAuthentication feature, users enable a time-based one-time password (TOTP) from an authenticator app by scanning a QR code, you store the encrypted secret and a set of single-use recovery codes on the user, and after the password step the login flow asks for a code. Options like requiring the user to confirm the first code before 2FA turns on, and asking for the password before enabling it, are in the feature's config.

Passkeys go further: a passkey (WebAuthn) replaces the password with a cryptographic key pair, where the private key stays on the user's device and a fingerprint or PIN unlocks it, so there is nothing to phish. Support for passkeys is available in recent Laravel starter kits and Fortify releases, but this area changes quickly, so follow the current documentation for your version rather than copying older snippets.

Both topics also need database columns (for example a column holding the encrypted 2FA secret), which Fortify's published migrations add. They are optional: enable them when your users' data justifies the extra friction.

Never roll your own reset or verification flow with an unsigned link, a token that is stored in plain text, or a link that never expires. If you do not use Fortify, use the framework's Password broker and signed routes, as shown above.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does it mean that Fortify is "headless"?

    Fortify provides endpoints and logic; you tell it which views to show with methods such as Fortify::loginView().
  2. 2. Where would you change which fields are required when a user registers while using Fortify?

    Fortify delegates user creation to an action class in your own application, so you edit validation and creation there.
  3. 3. Why is an email verification link signed?

    The signature is an HMAC of the URL made with the secret application key. Any tampering changes the expected value.
  4. 4. How does the password broker store reset tokens?

    Storing only a hash of the token, like a password, means the database alone is not enough to reset an account. Tokens also expire and are deleted after use.
  5. 5. What does the password.confirm middleware do?

    It protects risky actions by requiring a recent password confirmation, tracked in the session until password_timeout passes.

Summary

  • Fortify is the headless authentication backend behind the starter kits: you enable features in config/fortify.php and register your own views.
  • Business logic lives in editable action classes under app/Actions/Fortify, such as CreateNewUser.
  • Email verification uses MustVerifyEmail, a signed URL (HMAC with the app key, optional expiry) and the verified middleware.
  • Password reset uses the Password broker: hashed tokens in password_reset_tokens, an expiry (60 minutes by default), a throttle and one-time use.
  • The password.confirm middleware re-checks the password for sensitive actions within a configurable window.
  • 2FA (TOTP and recovery codes) is a Fortify feature; passkeys are newer, so check the documentation for your version.

Next: API Authentication with Sanctum