Laravel 12 Authentication: Secure Your App Like a Pro!

Laravel 12 Authentication: Secure Your App Like a Pro!

Ever worried about hackers breaking into your Laravel app? πŸ” Whether you're building a simple blog or a full-scale SaaS platform, authentication is your app's first line of defense.

Laravel 12 makes authentication easy, secure, and customizable. In this guide, we’ll cover:

βœ… Built-in Auth Systems (Breeze, Jetstream, Sanctum)
βœ… Custom Authentication (Manual Login & Registration)
βœ… Advanced Security (2FA, Rate Limiting, Password Hashing)

Let’s lock things down! πŸ”’


πŸ”₯ Why Authentication Matters

Before diving into code, let's understand why authentication is crucial:

βœ” Protects User Data – Prevents unauthorized access.
βœ” Prevents Attacks – Blocks brute force & credential stuffing.
βœ” Enhances Trust – Users feel safe using your app.


πŸ›  1. Laravel’s Built-in Auth Solutions

Laravel offers three powerful tools for authentication:

πŸ”Ή Laravel Breeze (Simple & Lightweight)

Perfect for beginners! It includes:

  • Login/Registration
  • Password Reset
  • Email Verification

Installation:

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

πŸ”Ή Laravel Jetstream (Advanced Features)

Need more? Jetstream adds:

  • Two-Factor Authentication (2FA)
  • API Support (Sanctum)
  • Team Management

Installation:

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

πŸ”Ή Laravel Sanctum (API Authentication)

Building a mobile app or SPA? Sanctum provides token-based auth.

Installation:

composer require laravel/sanctum  
php artisan sanctum:install  
php artisan migrate  

πŸ” 2. Custom Authentication (Manual Setup)

Sometimes, you need full control. Let’s build auth from scratch!

πŸ”Ή Step 1: Create Login & Register Routes

// routes/web.php  
Route::get('/register', [AuthController::class, 'showRegister'])->name('register');  
Route::post('/register', [AuthController::class, 'register']);  

Route::get('/login', [AuthController::class, 'showLogin'])->name('login');  
Route::post('/login', [AuthController::class, 'login']);  

Route::post('/logout', [AuthController::class, 'logout'])->name('logout');  

πŸ”Ή Step 2: Build the Auth Controller

// app/Http/Controllers/AuthController.php  
public function register(Request $request)  
{  
    $validated = $request->validate([  
        'name' => 'required|string|max:255',  
        'email' => 'required|email|unique:users',  
        'password' => 'required|confirmed|min:8',  
    ]);  

    $user = User::create([  
        'name' => $validated['name'],  
        'email' => $validated['email'],  
        'password' => Hash::make($validated['password']),  
    ]);  

    Auth::login($user);  
    return redirect('/dashboard');  
}  

public function login(Request $request)  
{  
    $credentials = $request->validate([  
        'email' => 'required|email',  
        'password' => 'required',  
    ]);  

    if (Auth::attempt($credentials)) {  
        return redirect('/dashboard');  
    }  

    return back()->withErrors(['email' => 'Invalid credentials!']);  
}  

πŸ”Ή Step 3: Protect Routes with Middleware

Route::middleware('auth')->group(function () {  
    Route::get('/dashboard', [DashboardController::class, 'index']);  
});  

🚨 3. Advanced Security Measures

πŸ”Ή Two-Factor Authentication (2FA)

Use Laravel Fortify or Jetstream for 2FA.

Example (Fortify):

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

πŸ”Ή Rate Limiting (Prevent Brute Force Attacks)

// app/Http/Middleware/ThrottleLogins.php  
Route::post('/login', [AuthController::class, 'login'])  
    ->middleware('throttle:5,1'); // 5 attempts per minute  

πŸ”Ή Password Hashing (Never Store Plain Text!)

Laravel automatically hashes passwords using bcrypt:

$user->password = Hash::make('secure123');  

πŸ“Š 4. Testing Your Authentication

βœ” Manual Testing – Try logging in with wrong credentials.
βœ” PHPUnit Testing – Automate security checks.

Example Test:

public function test_login_fails_with_wrong_password()  
{  
    $user = User::factory()->create();  

    $response = $this->post('/login', [  
        'email' => $user->email,  
        'password' => 'wrongpass',  
    ]);  

    $response->assertSessionHasErrors();  
}  

🎯 Key Takeaways

βœ” Use Breeze/Jetstream for quick setup
βœ” Build custom auth for full control
βœ” Enable 2FA & rate limiting for security
βœ” Always hash passwords
βœ” Test authentication flows


πŸš€ Final Thoughts

Laravel 12 makes authentication effortless and secure. Whether you use Breeze, Jetstream, or custom auth, your app will be locked down tight.

Got questions? Drop a comment below! πŸ’¬πŸ‘‡

Happy coding! πŸ’»πŸ”₯

Discussion

Comments

No comments yet. Be the first to comment.

Browse the project library

Projects to explore next

Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.

All projects