Authentication in Laravel: Login, Logout, Reset Password

Authentication in Laravel: Login, Logout, Reset Password

Laravel provides one of the most comprehensive, flexible, and secure authentication systems available in modern PHP frameworks. From simple username/password login flows to multi-factor authentication (MFA), OAuth2 servers, API token management, and social logins, Laravel’s ecosystem offers first-party packages and conventions that let developers focus on business logic rather than reinventing auth. In this extensive guide, we will cover every aspect of authentication in Laravel, including:

  • Introduction to Laravel’s Auth Philosophy
  • Built‑In Scaffolding: Breeze, Jetstream, and Fortify
  • Customizing Your User Model, Guards, and Providers
  • Role‑Based and Permission‑Based Authorization
  • Session Management and Throttling
  • API Authentication: Sanctum and Passport
  • Social Logins via Socialite
  • Multi‑Factor Authentication (MFA)
  • Password Security and Hashing Strategies
  • Best Practices for Production Security
  • Scaling Authentication: Caching, Sessions, and Redis
  • Monitoring, Auditing, and Logging Auth Events
  • Common Pitfalls and Troubleshooting
  • Migration Paths for Legacy Apps
  • Conclusion

1. Laravel’s Authentication Philosophy

At its core, Laravel’s goal is to give you a robust, secure foundation out of the box while letting you customize every piece. Key principles include:

  • Convention Over Configuration: sensible defaults for user tables, routes, and controllers.
  • Separation of Concerns: guards, providers, middleware, and policies are decoupled.
  • First‑Party Starter Kits: Breeze, Jetstream, and Fortify offer everything from UI to backend logic.
  • Extensible Core: swap out models, hashers, guards, and even the entire user table if needed.

This means you can get started with a working login system in minutes, but still dive deep for custom requirements.

2. Built‑In Scaffolding: Breeze, Jetstream, Fortify

2.1 Laravel Breeze

Laravel Breeze is the simplest starter kit. It uses Blade templates, minimal CSS, and no JavaScript frameworks.

Installation:

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate

Features:

  • Login, registration, password resets, email verification.
  • Tailwind CSS–driven UI without heavy frameworks.
  • Simplicity ideal for small apps or learning purposes.

2.2 Laravel Jetstream

Jetstream extends Breeze, adding advanced features and offering two front‑end stacks: Livewire/Blade and Inertia/Vue.

Install:

composer require laravel/jetstream
php artisan jetstream:install livewire    # or inertia
npm install && npm run dev
php artisan migrate

Out‑of‑the‑box:

  • Two‑factor authentication with recovery codes.
  • API tokens management.
  • Session management (logout other browser sessions).
  • Profile & team management (if desired).

Jetstream generates a /dashboard route and mounting points for user settings, token management, and MFA UI.

2.3 Laravel Fortify

Fortify is strictly the backend: it registers routes and logic but no UI. You decide how to build your forms or APIs.

Install:

composer require laravel/fortify
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
php artisan migrate

Capabilities:

  • Login, registration, password reset, email verification.
  • Password confirmation and reset throttling.
  • Two‑factor authentication logic (no QR code UI).

Fortify’s service provider lets you hook into events and customize responses, enabling SPA or mobile-tailored flows.

3. Customizing the User Model, Guards & Providers

Laravel’s User model and users table are defaults. But real-world apps often require additional fields or multiple user types.

3.1 Adding Custom Fields

  1. Migration:
  2. Schema::table('users', function (Blueprint $table) {
        $table->string('phone')->nullable();
        $table->boolean('is_premium')->default(false);
    });
  3. Model:
  4. class User extends Authenticatable
    {
        protected $fillable = [
            'name','email','password','phone','is_premium',
        ];
    }
  5. Registration & Validation:
    • Update create method in RegisterController or your Fortify callback.
    • Validate new fields in RegisterRequest or a custom FormRequest.

3.2 Multiple Guards and Providers

If you have admins, customers, or other user types with separate tables:

// config/auth.php

'guards' => [
    'web' => ['driver'=>'session','provider'=>'users'],
    'admin'=> ['driver'=>'session','provider'=>'admins'],
],
'providers' => [
    'users' => ['driver'=>'eloquent','model'=>App\Models\User::class],
    'admins'=> ['driver'=>'eloquent','model'=>App\Models\Admin::class],
],

In controllers or middleware, you can specify:

if (Auth::guard('admin')->attempt($credentials)) {
    // redirect to admin dashboard
}

Middleware example:

// app/Http/Middleware/RedirectIfAdminNot
public function handle(Request $request, Closure $next)
{
    if (!Auth::guard('admin')->check()) {
        return redirect()->route('admin.login');
    }
    return $next($request);
}

4. Role‑Based and Permission‑Based Authorization

Authentication is identity. Authorization is permission.

4.1 Gates

Gates are simple closures:

Gate::define('edit-post', function(User $user, Post $post) {
    return $user->id === $post->author_id;
});

Check it:

if (Gate::allows('edit-post', $post)) { /* show edit button */ }

4.2 Policies

Policies group logic per model. Generate one:

php artisan make:policy PostPolicy --model=Post

Implement methods like view, update, delete. Register in AuthServiceProvider:

protected \$policies = [ Post::class => PostPolicy::class ];

Usage in controllers:

$this->authorize('update', \$post);

4.3 Package Ecosystem

  • Spatie Laravel-Permission: Roles and permissions stored in database tables, with caching.
  • Bouncer: Fluent, code‑centric role and ability definitions.

Install and configure these to manage large permission sets.

5. Session Management, Throttling & Security Settings

5.1 Session Configuration

In config/session.php:

  • driver: file, cookie, database, redis, etc.
  • lifetime, expire_on_close.
  • secure, http_only, same_site.

For high‑security apps, prefer redis or database drivers to scale across servers.

5.2 Login Throttling

Laravel’s ThrottleRequests middleware works out‑of‑the‑box for rate limiting login routes:

Route::post('/login', [LoginController::class,'login'])->middleware('throttle:5,1');

Alternatively, use Fortify’s built‑in throttle by setting:

RateLimiter::for('login', function(Request \$request) {
    return Limit::perMinute(5)->by(\$request->email.\$request->ip());
});

5.3 Session Invalidation

To log out everywhere:

Auth::user()->tokens()->delete(); // for Sanctum tokens
$request->session()->invalidate();
$request->session()->regenerateToken();

6. API Authentication: Sanctum vs Passport

6.1 Laravel Sanctum

Sanctum offers both token-based and SPA cookie-based auth.

Token Example:

// Issue token
\$token = Auth::user()->createToken('mobile')->plainTextToken;
// Use it
"Authorization: Bearer {token}"

SPA Flow:

  • CSRF-protected cookie session.
  • sanctum/csrf-cookie endpoint.
  • Authenticated automatically.

Sanctum stores tokens in personal_access_tokens table and hashes names.

6.2 Laravel Passport (OAuth2)

Passport turns your app into an OAuth2 server.

Install:

composer require laravel/passport
aartisan migrate
php artisan passport:install

Routes & Tokens:

// AuthServiceProvider
Passport::routes();

Clients can request tokens via:

  • Password grant: username/password -> access & refresh tokens.
  • Client credentials, auth code, implicit.

Passport issues JWT‑style tokens with configurable TTLs.

7. Social Logins with Socialite

Use Socialite for OAuth logins (Google, Facebook, GitHub, LinkedIn, etc.)

Install:

composer require laravel/socialite

Configure in config/services.php:

'github' => [
    'client_id'=>env('GITHUB_ID'),
    'client_secret'=>env('GITHUB_SECRET'),
    'redirect'=>env('GITHUB_REDIRECT'),
],

Routes:

Route::get('login/github','Auth\SocialController@redirect');
Route::get('login/github/callback','Auth\SocialController@callback');

Controller:

public function callback() {
    \$socialUser = Socialite::driver('github')->user();
    // find or create local user
    Auth::login(\$user);
    return redirect('/dashboard');
}

Handle edge cases: missing emails, conflicting accounts, account linking UI.

8. Multi‑Factor Authentication (MFA)

For sensitive apps, add a second factor via TOTP (e.g. Google Authenticator) or SMS.

8.1 TOTP with pragmarx/google2fa-laravel

Install:

composer require pragmarx/google2fa-laravel

Setup:

  • Generate secret and QR code on profile page.
  • Store secret hashed in two_factor_secret.
  • On login, after password success, redirect to TOTP entry form.
  • Verify with Google2FA::verifyKey().

8.2 SMS & Email One‑Time Codes

Use Twilio or AWS SNS to send codes. Generate random code, store hashed in DB with timestamp, validate on entry, and expire after 5–10 minutes.

9. Password Security and Hashing Strategies

Laravel uses Bcrypt by default. You can configure hashers in config/hashing.php:

'driver'=>'argon2id',
'argon'=>[
    'memory'=>1024,'threads'=>2,'time'=>2
],

Never store plain text. Use Hash::make(\$password) and Hash::check(\$input, \$hash).

10. Best Practices for Production

  • Enforce HTTPS and HSTS.
  • Set SESSION_SECURE_COOKIE and CSRF_COOKIE_SECURE to true.
  • Enable bcrypt or argon2id, avoid outdated MD5 or SHA1.
  • Regularly rotate keys and tokens.
  • Use CSP headers to prevent XSS.
  • Implement content security policies and X-Frame-Options.

11. Scaling Authentication

  • Store sessions in Redis or database for horizontal scaling.
  • Cache permissions and roles (Spatie Permission supports caching).
  • Offload OAuth2 operations via queues (Passport’s RefreshTokenController).

12. Monitoring, Auditing, Logging

  • Use Laravel’s Auth events: Login, Logout, Lockout, Registered.
  • Listen in EventServiceProvider to write to logs or audit tables.
  • Integrate with third‑party monitoring (Sentry, New Relic) for suspicious activity.

13. Common Pitfalls

  • Swapping user models mid‑project without fresh migrations.
  • Ignoring CSRF on stateful routes when using Sanctum.
  • Not invalidating sessions/tokens on password change.
  • Overlooking throttle configuration, leading to brute‑force vulnerabilities.

14. Migrating Legacy Apps

  • Use Fortify for backend-only migration of old custom auth.
  • Gradually adopt Sanctum for APIs while maintaining old token systems.
  • Write compatibility layers in middleware to unify auth guards.

15. Conclusion

Laravel’s authentication stack—from Breeze’s simplicity to Passport’s complete OAuth2 flows—offers unmatched flexibility. By following conventions, leveraging first‑party packages, and adhering to best practices, you can build authentication systems that are secure, user‑friendly, and scalable. Dive into the official documentation, experiment with these tools, and tailor each layer—guards, providers, policies—to your application’s needs.

Happy coding and secure authenticating!


#Laravel authentication #Laravel Breeze #Laravel Jetstream #Laravel Fortify #custom guards #auth providers #role‑based access #permission management #Laravel Sanctum #Laravel Passport #API tokens #OAuth2 #socialite #social login #multi‑factor authentication

Subscribe to our newsletter

12k+

Subscribers

Weekly

Frequency

Free

Always