Security Best Practices

Authentication

Use Laravel's built-in authentication features for secure user login and registration. Use Laravel Breeze, Jetstream, or Fortify for modern authentication scaffolding.

  • Store passwords securely using bcrypt (default in Laravel).
  • Never store plain text passwords.
  • Use multi-factor authentication (MFA) for sensitive applications.
  • Always validate user credentials on the server side.

Example:

// Register a new user
$user = User::create([
    'name' => $request->name,
    'email' => $request->email,
    'password' => bcrypt($request->password),
]);

Authorization

Use Laravel's policies and gates to control access to resources and actions.

  • Define policies for models (e.g., UserPolicy, PostPolicy).
  • Use gates for simple, closure-based authorization.
  • Always check authorization before performing sensitive actions.

Example:

// In a policy
public function update(User $user, Post $post) {
    return $user->id === $post->user_id;
}

// In a controller
$this->authorize('update', $post);

Protecting Routes

Protect sensitive routes with authentication and authorization middleware.

// Good
Route::middleware('auth')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});
// Bad
Route::get('/dashboard', [DashboardController::class, 'index']);
  • Use auth middleware for user authentication.
  • Use custom middleware for role-based access control.

Validation and Sanitization

Always validate and sanitize user input to prevent security vulnerabilities.

  • Use Laravel's validation rules in Form Request classes or controllers.
  • Avoid manual sanitization; rely on validation and escaping in views.

Example:

// Good
$request->validate([
    'name' => 'required|string|max:255',
    'email' => 'required|string|email|max:255|unique:users',
]);
// Bad
$name = filter_var($request->input('name'), FILTER_SANITIZE_STRING);
$email = filter_var($request->input('email'), FILTER_SANITIZE_EMAIL);

Additional Best Practices

  • Use CSRF protection for all forms (@csrf Blade directive).
  • Escape output in Blade templates ({{ $variable }}) to prevent XSS.
  • Use HTTPS for all production environments.
  • Limit file upload types and validate file size and content.
  • Regularly update dependencies to patch security vulnerabilities.

Example: Secure Form

<form method="POST" action="/profile">
    @csrf
    <input type="text" name="name" value="{{ old('name') }}">
    <button type="submit">Update</button>
</form>

.htaccess Security Implementation

Root Directory (.htaccess)

# Disable directory listing
Options -Indexes

# Redirect all requests to public folder
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]

# Block access to all files in root
<Files *>
    Order allow,deny
    Deny from all
</Files>

Public Directory (.htaccess) - Enhanced Security

# Disable directory listing and multi-views
Options -MultiViews -Indexes

# Search engine blocking
Header set X-Robots-Tag "noindex, nofollow, noarchive, nosnippet, noimageindex"

# Security headers
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Content-Type-Options "nosniff"
Header unset X-Powered-By
Header unset Server

# Block sensitive file types
<FilesMatch "\.(env|json|config.js|md|gitignore|gitattributes|lock|bak|sql|log|inc|dist)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Block sensitive directories
<FilesMatch "(\.git|vendor|storage|node_modules|tests)">
    Order allow,deny
    Deny from all
</FilesMatch>

Directory Protection

  • Index files deployed: Added index.html to all sensitive directories with 403 Forbidden messages
  • Storage directory secured: Moved storage outside web-accessible directories
  • Upload directory isolation: Created separate, secured upload directories with access controls

Search Engine Protection

robots.txt Implementation

User-agent: *
Disallow: /
Crawl-delay: 10

Meta Tag Protection

<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">

HTTP Header Security

# Added to .htaccess
Header set X-Robots-Tag "noindex, nofollow, noarchive, nosnippet, noimageindex"

Laravel Application Security

Environment Configuration

  • App debug disabled: APP_DEBUG=false in all environments
  • Environment protection: Enhanced .env file security
  • Error reporting: Limited sensitive data in error messages

File Upload Security

// Enhanced upload validation
'upload' => [
    'max_size' => 10240, // 10MB
    'allowed_mimes' => ['jpg', 'png', 'pdf', 'doc', 'docx'],
    'blocked_extensions' => ['php', 'exe', 'sh', 'js'],
    'storage_path' => 'secured_uploads/', // Outside public directory
]

Route Protection

// Added route middleware for demo environment
Route::group(['middleware' => ['demo.protection']], function() {
    // All demo routes
});

Access Control Implementation

Directory Permissions

# Updated file permissions
chmod 755 storage/
chmod 755 bootstrap/cache/
chmod 644 .env
chmod 644 .htaccess
chmod 600 storage/app/private/

Advanced Security Topics

API Rate Limiting

Use Laravel's built-in rate limiting middleware to protect APIs from abuse.

Route::middleware('throttle:60,1')->group(function () {
    // API routes
});
  • Configure limits in app/Http/Kernel.php and use throttle middleware in routes.

Task Scheduling Security

  • Use Laravel's scheduler for automated tasks (e.g., backups, emails) and ensure scheduled commands are secure and do not expose sensitive data.
  • Restrict access to scheduled tasks and monitor logs for suspicious activity.

WebSockets & Real-Time Events Security

  • Use secure broadcasting drivers (Pusher, Redis) and configure authentication for private channels.
  • Validate and sanitize all data sent via WebSockets.

API Authentication (Sanctum/Passport)

  • Use Laravel Sanctum for token-based authentication in SPAs and mobile apps.
  • Use Laravel Passport for OAuth2 authentication for third-party integrations.
  • Store tokens securely and use HTTPS for all API traffic.

Multi-Tenancy Security

  • Isolate tenant data and configuration for SaaS applications.
  • Use database or schema separation and validate tenant access on every request.

Query Optimization & Security

  • Use parameterized queries and Eloquent ORM to prevent SQL injection.
  • Profile queries and monitor for suspicious or expensive operations.

Custom Artisan Commands Security

  • Restrict access to custom commands and avoid exposing sensitive operations via CLI.
  • Log command execution and monitor for unauthorized usage.

Hosting Security (cPanel/VPS/DigitalOcean)

cPanel Hosting

  • Point document root to public folder for security.
  • Set up .env file and correct file permissions.
  • Use cPanel's Cron Jobs for secure scheduling.
  • Configure SSL certificates via cPanel for HTTPS.
  • Restrict access to sensitive files and directories via .htaccess.

VPS/DigitalOcean Hosting

  • Use SSH keys for secure server access.
  • Set up Nginx or Apache to serve only the Laravel public directory.
  • Use Supervisor to manage queue workers securely.
  • Configure firewall rules to restrict access to sensitive ports.
  • Set up automated backups and monitoring (e.g., UptimeRobot, Datadog).
  • Regularly update OS packages and PHP extensions for security.

Deployment Automation Security

  • Use CI/CD pipelines for automated, secure deployments.
  • Use Envoyer, Deployer, or custom scripts for zero-downtime deployments.
  • Restrict deployment access to trusted users.

Security Best Practices for Hosting

  • Disable directory listing and restrict access to sensitive files via .htaccess or Nginx config.
  • Set correct file and directory permissions (chmod 755 for directories, 644 for files).
  • Use SSL/TLS for all environments.
  • Monitor logs and set up alerts for suspicious activity.