Laravel Security Skill

285646 28567 Updated: 2026-07-15 14:27:49

This is an Agent security skill designed specifically for the Laravel framework, aimed at helping developers identify, prevent, and fix common security vulnerabilities. The skill covers core security areas such as SQL injection, XSS attacks, CSRF protection, authentication authorization, encryption and decryption, and provides automated security scanning, code auditing, and best practice recommendations. It is suitable for development, testing, and production environments of Laravel projects, significantly enhancing application security and reliability.

Install
bunx skills add https://github.com/affaan-m/ECC --skill laravel-security
Skill Details readonly

1. Skill Overview

This skill delivers a complete set of security best practice references for Laravel applications, covering end-to-end security dimensions from authentication & authorization through production deployment. It functions simultaneously as a standardized security audit checklist and hands-on implementation guide, enabling developers to identify and remediate potential security vulnerabilities during development.
Core Principle: Security controls must be implemented at every application layer — entrypoint middleware & form request validation, business logic authorization policies, and persistent data storage via field encryption & mass assignment safeguards.

2. Core Capabilities

2.1 Authentication & Authorization

Feature Implementation Guidance
API Authentication Use Laravel Sanctum or Passport for API auth; prioritize short-lived access tokens paired with refresh token workflows
Route Protection Secure sensitive endpoints via the auth:sanctum middleware
Token Lifecycle Management Revoke all tokens immediately upon user logout or account compromise
Password Security Store only hashed passwords generated via Hash::make(); never persist plaintext credentials. Enforce strict password validation rules: minimum 12 characters with mixed uppercase/lowercase letters, digits, and symbols
Model Policies for Granular Authorization Implement dedicated model policies; invoke $this->authorize() within controllers and service classes to enforce access rules
Route-Level Authorization Middleware Apply can:action,resource middleware directly on route definitions to enforce policy checks at the routing layer
 
// Protected API route example
Route::middleware('auth:sanctum')->get('/me', function (Request $request) {
    return $request->user();
});

// Inline controller policy authorization
$this->authorize('update', $project);

// Route-bound policy middleware
Route::put('/projects/{project}', [ProjectController::class, 'update'])
    ->middleware(['auth:sanctum', 'can:update,project']);

2. Input Validation & Data Sanitization

  • Always validate all user input via dedicated Form Request classes; never trust derived fields from raw request payloads
  • Enforce strict typed validation rules for all request parameters
  • Utilize Laravel’s official password broker component to manage secure password reset workflows

2.2 CSRF Protection

  • Keep the VerifyCsrfToken middleware globally enabled
  • Inject the @csrf Blade directive within all HTML form bodies
  • Transmit XSRF tokens via request headers for SPA frontend requests
  • For SPA + Sanctum deployments, confirm trusted stateful frontend domains are correctly configured in environment variables

2.3 Mass Assignment Protection

  • Explicitly define whitelisted editable fields using the $fillable model property or block all fields via $guarded = []
  • Never invoke Model::unguard() to disable mass assignment safeguards
  • Prefer DTO objects or explicit attribute mapping over wildcard mass assignment

2.4 SQL Injection Mitigation

  • Use Eloquent ORM or the query builder with automatic parameter binding for all database queries
  • If raw SQL statements are unavoidable, strictly use positional parameter binding to escape untrusted input
 
// Safe parameterized raw SQL
DB::select('select * from users where email = ?', [$email]);

2.5 XSS Prevention

  • Blade’s double curly brace syntax {{ }} automatically escapes output by default
  • Restrict raw unescaped HTML rendering with {!! !!} exclusively to pre-sanitized, trusted markup
  • Process rich user-submitted content with dedicated HTML sanitization libraries before rendering

2.6 Secure File Upload Handling

Inspection Item Specification
File Validation Enforce limits on file size, verified MIME types, and allowed file extensions
Storage Location Store uploaded assets outside the web-accessible public directory whenever possible
Malware Scanning Integrate virus/malware scanning pipelines for user uploads in high-risk environments
 
 
final class UploadInvoiceRequest extends FormRequest
{
    public function authorize(): bool
    {
        return (bool) $this->user()?->can('upload-invoice');
    }

    public function rules(): array
    {
        return [
            'invoice' => ['required', 'file', 'mimes:pdf', 'max:5120'],
        ];
    }
}

2.7 Rate Limiting

  • Apply throttle middleware to all authentication and write mutation endpoints
  • Enforce stricter rate limits for login, password reset, and OTP verification routes
RateLimiter::for('login', function (Request $request) {
    return [
        Limit::perMinute(5)->by($request->ip()),
        Limit::perMinute(5)->by(strtolower((string) $request->input('email'))),
    ];
});

2.8 Secret & Credential Governance

  • Never commit API keys, database credentials, or application secrets to source control
  • Store all sensitive values via environment variables or dedicated external secret management services
  • Immediately rotate all exposed secrets and invalidate all active user sessions upon credential leakage

2.9 Encrypted Database Attributes

Mark sensitive database columns as encrypted via model cast definitions to auto-encrypt/decrypt stored values:
protected $casts = [
    'api_token' => 'encrypted',
];

2.10 Security Response Headers

Inject standardized security headers via custom middleware:
Header Recommended Value
Content-Security-Policy default-src 'self'
Strict-Transport-Security max-age=31536000; add includeSubDomains; preload only when all subdomains enforce HTTPS
X-Frame-Options DENY
X-Content-Type-Options nosniff
Referrer-Policy no-referrer

2.11 CORS & API Exposure Hardening

  • Restrict allowed origin domains within config/cors.php to explicit trusted hosts
  • Avoid wildcard origin patterns for authenticated API routes
  • Whitelist only required HTTP methods and request headers for cross-origin requests

2.12 Logging & PII Redaction

  • Never log raw passwords, authentication tokens, or full payment card data
  • Redact all personally identifiable information within structured application logs
Log::info('User updated profile', [
    'user_id' => $user->id,
    'email' => '[REDACTED]',
    'token' => '[REDACTED]',
]);

2.13 Dependency Security Management

  • Execute composer audit on a regular cadence to scan vulnerable packages
  • Lock dependency versions tightly and apply security patch updates immediately upon disclosed CVEs

2.14 Signed Tamper-Proof URLs

Generate expiring, cryptographically signed URLs for secure temporary resource access:
$url = URL::temporarySignedRoute(
    'downloads.invoice',
    now()->addMinutes(15),
    ['invoice' => $invoice->id]
);

Route::get('/invoices/{invoice}/download', [InvoiceController::class, 'download'])
    ->name('downloads.invoice')
    ->middleware('signed');

3. Primary Use Cases

  1. New project security baseline setup
     
    Reference this full security framework during Laravel project initialization to build a complete hardened security foundation
  2. Security audits & code review
     
    Cross-reference the checklist during code reviews to identify common unmitigated security vulnerabilities
  3. Pre-production environment hardening
     
    Validate critical production configurations: APP_DEBUG=false, SESSION_SECURE_COOKIE=true, SESSION_SAME_SITE=lax/strict and related security flags
  4. Vulnerability remediation reference
     
    Quickly locate matching control implementations and official fixes when security defects are discovered
  5. Team secure coding training
     
    Serve as standardized secure coding specification documentation for Laravel engineering teams

4. Critical Guiding Principles

  1. Validate all untrusted input exclusively via Form Request classes with strict typed rules; never trust raw user payloads
  2. Hash all passwords with Hash::make(); plaintext password storage is prohibited
  3. Enforce mass assignment safeguards via $fillable / $guarded; avoid Model::unguard()
  4. Use parameter-bound database queries universally to eliminate SQL injection attack surface
  5. Encrypt sensitive persistent data using Laravel’s encrypted attribute casts
  6. Disable debug mode in production via APP_DEBUG=false
  7. All secrets are managed via environment variables, never committed to source control
  8. Redact all PII, passwords, and tokens within application log output

Summary

Laravel Security is a complete best-practice skillset for securing Laravel web applications, covering 15 core security domains: authentication & authorization, input sanitization, CSRF defense, mass assignment protection, SQLi/XSS mitigation, secure file uploads, rate limiting, secret management, encrypted database fields, security HTTP headers, CORS hardening, log PII redaction, dependency vulnerability scanning, and expiring signed URLs. It operates as both a actionable audit checklist and standardized secure coding specification, intended for Laravel developers implementing new project security baselines, conducting code security audits, hardening production deployments, and delivering team secure coding training.