Authentication
Authentication system in Laravel
Authentication in Laravel means identifying and verifying user identity. This system allows you to log users in, manage their sessions and control their access.
Main Authentication Features:
- <strong>Login/Logout</strong>: User login and logout
- <strong>Remember Me</strong>: Keeping session for long duration
- <strong>Password Reset</strong>: Password recovery
- <strong>Email Verification</strong>: Email verification
- <strong>Multi-factor Authentication</strong>: Multi-step authentication
- <strong>Session Management</strong>: Session management
- <strong>Guards</strong>: Different authentication methods
- <strong>Providers</strong>: User sources
Authentication Flow:
1. User submits credentials
2. Laravel validates credentials
3. User is authenticated
4. Session is created
5. User is redirected to protected route
Guards and Providers:
- <strong>Guards</strong>: Determine how user is authenticated (session, token, etc.)
- <strong>Providers</strong>: Determine where users are retrieved from (database, LDAP, etc.)
Security Features:
- Password hashing with bcrypt
- CSRF protection
- Rate limiting
- Session security
- Remember token encryption
Examples
Simple Login
<?php
use Illuminate\Support\Facades\Auth;
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('dashboard');
}
return back()->withErrors(['email' => 'Invalid credentials']);
Simple login with email and password.
Login with Remember Me
<?php
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// User will be remembered
return redirect()->intended('dashboard');
}
// Or explicitly
Auth::attempt($credentials, true); // Remember for 2 weeks
Login with remember me functionality.
Manual Authentication
<?php
$user = User::find(1);
// Login user without credentials
Auth::login($user);
// Login and remember
Auth::login($user, true);
// Login using user ID
Auth::loginUsingId(1);
// Check if authenticated
if (Auth::check()) {
$user = Auth::user();
}
// Get authenticated user
$user = Auth::user();
Manual authentication without credentials.
Logout
<?php
// Logout current user
Auth::logout();
// Logout and invalidate session
Auth::logout();
request()->session()->invalidate();
request()->session()->regenerateToken();
// Redirect after logout
return redirect('/')->after(function () {
Auth::logout();
});
Logging out user and invalidating session.
Password Reset
<?php
use Illuminate\Support\Facades\Password;
// Send password reset link
$status = Password::sendResetLink(
$request->only('email')
);
// Reset password
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function ($user, $password) {
$user->forceFill([
'password' => Hash::make($password)
])->save();
}
);
Password reset functionality.
Email Verification
<?php
// In User model
use Illuminate\Contracts\Auth\MustVerifyEmail;
class User extends Authenticatable implements MustVerifyEmail
{
//
}
// Send verification email
$user->sendEmailVerificationNotification();
// Check if verified
if ($user->hasVerifiedEmail()) {
// Email is verified
}
// Mark as verified
$user->markEmailAsVerified();
Email verification functionality.
Middleware Protection
<?php
// In routes
Route::middleware('auth')->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
});
});
// In controller
public function __construct()
{
$this->middleware('auth');
}
// Guest middleware (redirect if authenticated)
Route::middleware('guest')->group(function () {
Route::get('/login', [LoginController::class, 'show']);
});
Using auth middleware to protect routes.
Use Cases
- User login and logout
- Session management
- Password reset functionality
- Email verification
- Protected routes and resources
- Multi-guard authentication
- Remember me functionality
Common Mistakes
- Forgetting to validate credentials
- Using plain text passwords
- Forgetting CSRF protection
- Not using rate limiting
- Forgetting logout in sensitive operations
- Not using email verification
Best Practices
- Always validate credentials
- Use password hashing
- Use CSRF protection
- Use rate limiting
- Use email verification
- Configure session timeout
- Use secure cookies
Edge Cases
- Concurrent login attempts
- Session expiration
- Remember me token expiration
- Password reset token expiration
- Email verification in different timezones
- Multi-guard authentication
Performance Notes
- Use indexes for email and username
- Optimize session storage
- Use caching for frequently accessed user data
- Password hashing overhead is acceptable
- Use database indexes for authentication queries
Security Notes
- Always hash passwords
- Use CSRF protection
- Use rate limiting
- Use secure session configuration
- Enforce email verification
- Use strong password requirements
- Prevent session hijacking
Interview Points
- What is Authentication and how does it work?
- What is the difference between authentication and authorization?
- How can you reset password?
- How does remember me work?
- What is email verification and how is it implemented?
- What are Guards and Providers?
Version Notes
- Laravel 11.x: Improved performance in authentication
- Laravel 11.x: Better support for multi-factor authentication
- Laravel 10.x: Improved password reset
- Laravel 9.x: Improved session management