Broken Authentication in Laravel
How Broken Authentication Manifests in Laravel
Broken authentication in Laravel applications often stems from misconfigured middleware, insecure session handling, or improper use of Laravel's authentication features. Understanding these Laravel-specific patterns is crucial for both attackers and defenders.
One common vulnerability occurs when developers forget to apply the auth middleware to routes that should be protected. Consider this controller:
class UserController extends Controller
{
public function __construct()
{
// Missing auth middleware!
}
public function profile()
{
$user = User::find(1);
return view('profile', ['user' => $user]);
}
}Without the auth middleware, any user can access /profile and view the first user's data. The correct implementation would be:
public function __construct()
{
$this->middleware('auth');
}Another Laravel-specific issue involves session fixation. Laravel's default session driver is file-based, but if you're using database sessions without proper configuration, attackers might hijack sessions:
// Vulnerable: missing session regeneration
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard');
}
}The fix requires regenerating the session ID after successful authentication:
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('dashboard');
}Laravel's remember me functionality can also introduce vulnerabilities if not properly secured. The default implementation uses a persistent cookie, but without proper token rotation:
// In LoginController
protected function authenticated(Request $request, $user)
{
if ($request->has('remember')) {
// Ensure tokens are properly rotated
$user->tokens()->delete();
$user->tokens()->create([
'token' => Str::random(60),
'expires_at' => now()->addWeeks(4)
]);
}
}Password reset functionality is another critical area. Laravel's default password reset system is secure, but custom implementations often fail:
// Vulnerable: timing attack possible
public function reset(Request $request)
{
$user = User::where('email', $request->email)->first();
if ($user) {
// Reset logic
}
// Always return success to prevent enumeration
return response()->json(['status' => 'success']);
}Finally, API authentication in Laravel often suffers from broken token management. When using Laravel Sanctum or Passport without proper token revocation:
// Vulnerable: tokens never expire
$token = $user->createToken('api')->plainTextToken;
// Should have expiration: now()->addHours(2)Laravel-Specific Detection
Detecting broken authentication in Laravel requires both manual code review and automated scanning. middleBrick's Laravel-specific detection capabilities include scanning for these common patterns.
middleBrick's scanner automatically tests for missing authentication middleware by attempting to access routes that should be protected. It sends unauthenticated requests to endpoints like /api/user, /profile, and /admin, then analyzes the responses for sensitive data exposure.
The scanner also detects Laravel's default session configuration issues. It checks whether session cookies are properly configured with httponly, secure, and sameSite attributes. Here's what middleBrick looks for:
// middleBrick detects if you're using:
// - Default session lifetime (120 minutes)
// - Missing session encryption
// - Insecure session cookie settings
// - Missing session fixation protectionFor API authentication, middleBrick tests Laravel Sanctum and Passport implementations by attempting to use expired or invalid tokens, checking for proper error handling that doesn't leak information about valid user IDs or email addresses.
The scanner also analyzes your Laravel application's authentication routes. It checks for common vulnerabilities like:
- Missing rate limiting on login attempts
- Password reset tokens that don't expire
- Remember me tokens without proper rotation
- Missing two-factor authentication where appropriate
middleBrick's LLM/AI security module specifically tests Laravel applications that use AI features, checking for prompt injection vulnerabilities in Laravel's Blade templates or API responses that might expose system prompts or training data.
To use middleBrick for Laravel authentication scanning:
npm install -g middlebrick
middlebrick scan https://your-laravel-app.com/api/login
The CLI output will show Laravel-specific findings with severity levels and remediation guidance tailored to Laravel's authentication patterns.
Laravel-Specific Remediation
Fixing broken authentication in Laravel requires leveraging Laravel's built-in security features while following security best practices. Here are Laravel-specific remediation strategies.
First, always apply the auth middleware correctly. For controllers:
class SecureController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
// Only authenticated users can access this
return view('dashboard');
}
}For route groups:
Route::middleware(['auth'])->group(function () {
Route::get('/profile', [ProfileController::class, 'show']);
Route::get('/settings', [SettingsController::class, 'edit']);
});Session security is critical in Laravel. Configure your config/session.php file:
return [
'lifetime' => 120,
'expire_on_close' => false,
'encrypt' => true,
'cookie' => [
'path' => '/',
'domain' => env('SESSION_DOMAIN'),
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax',
],
];Always regenerate session IDs after login:
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('dashboard');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.'
]);
}For API authentication with Laravel Sanctum, implement proper token expiration:
// In your authentication service
public function createTokenWithExpiration(User $user, $name, $hours = 2)
{
$token = $user->createToken($name);
$token->token->expires_at = now()->addHours($hours);
$token->token->save();
return $token;
}Implement rate limiting on authentication endpoints:
Route::middleware(['auth:sanctum'])->group(function () {
Route::get('/user', [UserController::class, 'show']);
});
Route::middleware(['throttle:login,5'])->group(function () {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
});For password reset functionality, use Laravel's built-in system which is already secure:
use Illuminate\Support\Facades\Password;
public function sendResetLink(Request $request)
{
$request->validate(['email' => 'required|email']);
$status = Password::sendResetLink(
$request->only('email')
);
return $status === Password::RESET_LINK_SENT
? back()->with(['status' => __($status)])
: back()->withErrors(['email' => __($status)]);
}Finally, implement two-factor authentication for sensitive operations using Laravel's built-in features or packages like laravel/two-factor-auth.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |
Frequently Asked Questions
How does Laravel's default authentication compare to other frameworks?
Laravel's default authentication is more secure than many frameworks out of the box. It includes CSRF protection, secure session handling, and proper password hashing with bcrypt. However, developers often weaken this security by misconfiguring middleware, disabling security features, or implementing custom authentication that bypasses Laravel's protections. middleBrick specifically tests for these misconfigurations that are common in Laravel applications.
Can middleBrick detect broken authentication in Laravel applications?
Yes, middleBrick is specifically designed to detect broken authentication patterns in Laravel applications. It tests for missing middleware, insecure session configurations, weak password reset implementations, and API authentication issues. The scanner runs 12 security checks including authentication bypass attempts, session fixation testing, and rate limiting verification. It provides Laravel-specific remediation guidance and maps findings to OWASP API Top 10 categories.