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.
## 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
Configure Auth Guard:
In config/auth.php, ensure your default guard is set to web (or your preferred guard):
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
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();
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.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]);
}
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}
config/fortify.php:
'features' => [
Features::twoFactorAuthentication(),
],
Trigger 2FA setup:
POST /user/two-factor-authentication
Verify codes:
POST /user/two-factor-authentication/verify-code
UpdateUserProfileInformation:
PUT /user/profile-information
Update password via UpdateUserPassword:
PUT /user/password
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/.
auth middleware:
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', function () { ... });
});
Fortify::authenticate() in custom middleware to validate sessions.TwoFactorAuthenticated) in EventServiceProvider:
protected $listen = [
\Laravel\Fortify\Events\TwoFactorAuthenticated::class => [
\App\Listeners\LogTwoFactorAuth::class,
],
];
FortifyServiceProvider:
Fortify::authenticated(function (Request $request, User $user) {
return response()->json(['message' => 'Authenticated successfully']);
});
login, register, etc., which may conflict with existing routes.
Fix: Rename routes in FortifyServiceProvider:
Fortify::loginView(function () {
return route('custom.login');
});
// In FortifyServiceProvider.php
Fortify::ignoreRoutes();
Fortify::createApiRoutes();
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;
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
]);
});
VerifyEmail:
Fortify::verifyEmailUsing(function (Request $request) {
$request->user()->markEmailAsVerified();
return redirect()->intended('/dashboard');
});
// In AppServiceProvider
Fortify::authenticated(function (Request $request, User $user) {
\Log::info('User authenticated', ['user' => $user->id]);
});
$user = User::find(1);
$user->forceFill(['two_factor_secret' => 'SECRET'])->save();
event(new \Laravel\Fortify\Events\TwoFactorAuthenticated($user));
public function handle($request, Closure $next) {
\Log::info('Fortify Request', ['input' => $request->all()]);
return $next($request);
}
User model. Custom models require explicit configuration:
Fortify::userModel(\App\Models\CustomUser::class);
web guard. For custom guards (e.g., api), specify:
Fortify::authGuard('api');
How can I help you explore Laravel packages today?