{"slug":"laravel-security","title":"laravel-security","summary":"Laravel security best practices — authentication, authorization, Eloquent safety, CSRF, XSS prevention, API security, and secure deployment configurations. Use when reviewing Laravel auth, Eloquent safety, CSRF, XSS, API security, or deployment configuration.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:42.725786Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: laravel-security\ndescription: Laravel security best practices — authentication, authorization, Eloquent safety, CSRF, XSS prevention, API security, and secure deployment configurations. Use when reviewing Laravel auth, Eloquent safety, CSRF, XSS, API security, or deployment configuration.\nmetadata:\norigin: ECC</h2>\n<h1>Laravel Security Best Practices</h1>\n<p>Comprehensive security guidelines for Laravel applications to protect against common vulnerabilities.</p>\n<h2>When to Activate</h2>\n<ul>\n<li>Setting up Laravel authentication and authorization (Sanctum, Passport, Jetstream, Breeze)</li>\n<li>Implementing user roles, permissions, and policies</li>\n<li>Configuring production security settings and environment variables</li>\n<li>Reviewing Laravel applications for security vulnerabilities</li>\n<li>Deploying Laravel applications to production</li>\n<li>Writing secure Eloquent queries and migrations</li>\n</ul>\n<h2>Production Configuration</h2>\n<h3>Essential Production Settings</h3>\n<pre><code>// config/app.php\n'env' =&gt; env('APP_ENV', 'production'),\n'debug' =&gt; (bool) env('APP_DEBUG', false), // CRITICAL: Never true in production\n'key' =&gt; env('APP_KEY'), // Must be set: php artisan key:generate\n\n// config/session.php\n'secure' =&gt; env('SESSION_SECURE_COOKIE', true),\n'http_only' =&gt; true,\n'same_site' =&gt; 'lax',\n\n// Verify APP_KEY is set at boot\n// bootstrap/app.php or a service provider\nif (empty(config('app.key'))) {\n    throw new RuntimeException('APP_KEY is not set. Run: php artisan key:generate');\n}\n</code></pre>\n<h3>Environment File Security</h3>\n<pre><code># NEVER commit .env to version control\n# .gitignore already includes .env by default\n\n# Use .env.example with placeholders instead\nDB_PASSWORD=\nAPP_KEY=\nSANCTUM_TOKEN_PREFIX=\n\n# Validate required variables at boot\n// In AppServiceProvider::boot()\n$requiredKeys = ['app.key', 'database.connections.mysql.database', 'database.connections.mysql.username'];\nforeach ($requiredKeys as $key) {\n    if (empty(config($key))) {\n        throw new RuntimeException(\"Missing required config key: {$key}\");\n    }\n}\n</code></pre>\n<h3>HTTPS Enforcement</h3>\n<pre><code>// AppServiceProvider::boot() or middleware\nif (app()-&gt;environment('production')) {\n    URL::forceScheme('https');\n    request()-&gt;server-&gt;set('HTTPS', 'on');\n}\n\n// config/app.php for trusted proxies (load balancers)\n// Use specific IP ranges — * trusts all, allowing X-Forwarded-* spoofing\n// AWS: '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'\n'trusted_proxies' =&gt; ['10.0.0.0/8', '172.16.0.0/12'],\n\n// Force HTTPS in production via middleware\n// app/Http/Middleware/ForceHttps.php\npublic function handle($request, Closure $next)\n{\n    if (!$request-&gt;secure() &amp;&amp; app()-&gt;environment('production')) {\n        return redirect()-&gt;secure($request-&gt;getRequestUri());\n    }\n    return $next($request);\n}\n</code></pre>\n<h2>Authentication</h2>\n<h3>Sanctum (API Token Authentication)</h3>\n<pre><code>// config/sanctum.php\n'stateful' =&gt; explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(\n    '%s%s',\n    'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',\n    env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : ''\n)));\n\n'expiration' =&gt; 60 * 24, // Token expiration in minutes (null = never)\n'token_prefix' =&gt; env('SANCTUM_TOKEN_PREFIX', ''),\n\n// Issuing tokens with abilities\n$token = $user-&gt;createToken('api-token', ['read', 'write'])-&gt;plainTextToken;\n\n// Validate abilities on routes\nRoute::middleware('auth:sanctum')-&gt;group(function () {\n    Route::get('/orders', function () {\n        // User must have 'read' ability\n        abort_unless(Auth::user()-&gt;tokenCan('read'), 403);\n        // ...\n    })-&gt;middleware('abilities:read');\n\n    Route::post('/orders', function () {\n        // User must have 'write' ability\n        abort_unless(Auth::user()-&gt;tokenCan('write'), 403);\n        // ...\n    })-&gt;middleware('abilities:write');\n});\n</code></pre>\n<h3>Password Security</h3>\n<pre><code>// config/hashing.php\n// Default is bcrypt. Argon2id is stronger.\n'bcrypt' =&gt; [\n    'rounds' =&gt; env('BCRYPT_ROUNDS', 12), // Increase for stronger hashing\n],\n\n'argon' =&gt; [\n    'memory' =&gt; 65536,\n    'threads' =&gt; 4,\n    'time' =&gt; 4,\n],\n\n// Password validation in RegisterRequest\npublic function rules(): array\n{\n    return [\n        'password' =&gt; [\n            'required',\n            'confirmed',\n            Password::min(12)\n                -&gt;letters()\n                -&gt;mixedCase()\n                -&gt;numbers()\n                -&gt;symbols()\n                -&gt;uncompromised(), // Checks haveibeenpwned\n        ],\n    ];\n}\n\n// Rate limit login attempts\n// App\\Http\\Controllers\\Auth\\AuthenticatedSessionController\nprotected function authenticated(Request $request, $user)\n{\n    if ($user-&gt;wasRecentlyLockedOut()) {\n        // Notify user of suspicious login\n        $user-&gt;notify(new SuspiciousLoginNotification($request-&gt;ip()));\n    }\n}\n</code></pre>\n<h3>Session Management</h3>\n<pre><code>// config/session.php\n'driver' =&gt; env('SESSION_DRIVER', 'database'), // database/redis &gt; file\n'lifetime' =&gt; env('SESSION_LIFETIME', 120),\n'expire_on_close' =&gt; env('SESSION_EXPIRE_ON_CLOSE', false),\n'encrypt' =&gt; env('SESSION_ENCRYPT', false),\n\n// Regenerate session on login\n// App\\Http\\Controllers\\Auth\\AuthenticatedSessionController\npublic function store(LoginRequest $request): RedirectResponse\n{\n    $request-&gt;authenticate();\n    $request-&gt;session()-&gt;regenerate(); // CRITICAL: prevents session fixation\n    return redirect()-&gt;intended(RouteServiceProvider::HOME);\n}\n\n// Invalidate session on logout\npublic function destroy(Request $request): RedirectResponse\n{\n    Auth::guard('web')-&gt;logout();\n    $request-&gt;session()-&gt;invalidate();\n    $request-&gt;session()-&gt;regenerateToken();\n    return redirect('/');\n}\n</code></pre>\n<h2>Authorization</h2>\n<h3>Gates</h3>\n<pre><code>// App\\Providers\\AuthServiceProvider\nuse App\\Models\\Post;\nuse App\\Models\\User;\nuse Illuminate\\Support\\Facades\\Gate;\n\npublic function boot(): void\n{\n    Gate::define('update-post', function (User $user, Post $post): bool {\n        return $user-&gt;id === $post-&gt;user_id;\n    });\n\n    Gate::define('publish-post', function (User $user): bool {\n        return $user-&gt;role === 'editor' || $user-&gt;role === 'admin';\n    });\n\n    // Using before() for super-admin override\n    Gate::before(function (User $user, string $ability): ?bool {\n        if ($user-&gt;role === 'super-admin') {\n            return true; // Grants all abilities\n        }\n        return null; // Fall through to normal checks\n    });\n}\n\n// Usage in controllers\npublic function update(Request $request, Post $post): RedirectResponse\n{\n    Gate::authorize('update-post', $post);\n    // Or: $this-&gt;authorize('update-post', $post);\n    // Or: abort_unless(Auth::user()-&gt;can('update-post', $post), 403);\n    // ...\n}\n</code></pre>\n<h3>Policies</h3>\n<pre><code>// App\\Policies\\PostPolicy\nclass PostPolicy\n{\n    use HandlesAuthorization;\n\n    public function viewAny(?User $user): bool\n    {\n        return true; // Public listing\n    }\n\n    public function view(?User $user, Post $post): bool\n    {\n        return $post-&gt;is_published || ($user &amp;&amp; $user-&gt;id === $post-&gt;user_id);\n    }\n\n    public function create(User $user): bool\n    {\n        return $user-&gt;hasVerifiedEmail(); // Must verify email first\n    }\n\n    public function update(User $user, Post $post): bool\n    {\n        return $user-&gt;id === $post-&gt;user_id;\n    }\n\n    public function delete(User $user, Post $post): bool\n    {\n        return $user-&gt;id === $post-&gt;user_id &amp;&amp; $post-&gt;created_at-&gt;diffInDays(now()) &lt;= 30;\n    }\n\n    public function restore(User $user, Post $post): bool\n    {\n        return $user-&gt;role === 'admin';\n    }\n\n    public function forceDelete(User $user, Post $post): bool\n    {\n        return $user-&gt;role === 'super-admin';\n    }\n}\n\n// Register in AuthServiceProvider\nprotected $policies = [\n    Post::class =&gt; PostPolicy::class,\n];\n\n// Controller usage\npublic function show(Post $post): View\n{\n    $this-&gt;authorize('view', $post);\n    return view('posts.show', compact('post'));\n}\n\n// Blade usage\n@can('update', $post)\n    &lt;a href=\"{{ route('posts.edit', $post) }}\"&gt;Edit&lt;/a&gt;\n@endcan\n\n@cannot('update', $post)\n    &lt;span&gt;You cannot edit this post&lt;/span&gt;\n@endcannot\n</code></pre>\n<h3>Middleware Authorization</h3>\n<pre><code>// Using middleware in routes\nRoute::put('/posts/{post}', [PostController::class, 'update'])\n    -&gt;middleware('can:update,post');\n\nRoute::get('/posts/create', [PostController::class, 'create'])\n    -&gt;middleware('can:create,App\\Models\\Post');\n\n// Custom authorization middleware\n// app/Http/Middleware/CheckRole.php\nclass CheckRole\n{\n    public function handle(Request $request, Closure $next, string $role): mixed\n    {\n        if (!$request-&gt;user() || $request-&gt;user()-&gt;role !== $role) {\n            abort(403, 'Unauthorized. This area requires role: ' . $role);\n        }\n        return $next($request);\n    }\n}\n\n// Register in Kernel\nprotected $routeMiddleware = [\n    'role' =&gt; \\App\\Http\\Middleware\\CheckRole::class,\n];\n\n// Route usage\nRoute::middleware(['auth', 'role:admin'])-&gt;group(function () {\n    Route::get('/admin', [AdminController::class, 'index']);\n});\n</code></pre>\n<h2>Eloquent Security</h2>\n<h3>Mass Assignment Protection</h3>\n<pre><code>// BAD: $guarded = [] allows ALL columns to be mass-assigned\n// NEVER use $guarded = [] in production\n\n// GOOD: Whitelist fillable attributes\nfinal class User extends Authenticatable\n{\n    protected $fillable = [\n        'name',\n        'email',\n        'phone',\n        'avatar',\n    ];\n    // NEVER add 'role', 'is_admin', 'is_verified' here\n}\n\n// GOOD: Explicitly control which fields can be filled in requests\npublic function store(StoreUserRequest $request): RedirectResponse\n{\n    $user = User::create($request-&gt;safe()-&gt;only([\n        'name', 'email', 'phone', 'avatar'\n    ]));\n    // $request-&gt;safe() uses validated data only\n    // $request-&gt;only() is NOT safe on its own without validation rules\n}\n\n// BAD: Creating a user with request data directly\nUser::create($request-&gt;all()); // VULNERABLE to mass assignment!\n\n// BETTER: Use DTOs for creation\n$user = User::create($request-&gt;validated()); // Only validated fields\n</code></pre>\n<h3>SQL Injection Prevention</h3>\n<pre><code>// GOOD: Eloquent automatically parameterizes queries\nUser::where('email', $userInput)-&gt;first();\nUser::whereRaw('email = ?', [$userInput])-&gt;first();\n\n// GOOD: Query Builder also parameterizes\nDB::table('users')-&gt;where('email', $userInput)-&gt;first();\nDB::select('SELECT * FROM users WHERE email = ?', [$userInput]);\n\n// BAD: Raw string interpolation\nDB::select(\"SELECT * FROM users WHERE email = '{$userInput}'\"); // VULNERABLE!\nUser::whereRaw(\"email = '{$userInput}'\")-&gt;first(); // VULNERABLE!\n\n// BAD: whereRaw/orderByRaw with unescaped input\nUser::orderByRaw($userInput); // VULNERABLE!\nUser::groupByRaw($userInput); // VULNERABLE!\n\n// BAD: DB::statement with concatenation\nDB::statement(\"INSERT INTO users (email) VALUES ('{$userInput}')\"); // VULNERABLE!\n</code></pre>\n<h3>Attribute Casting</h3>\n<pre><code>final class User extends Authenticatable\n{\n    protected $casts = [\n        'email_verified_at' =&gt; 'datetime',\n        'is_admin' =&gt; 'boolean', // Cast to boolean prevents string injection\n        'settings' =&gt; 'array', // Automatically json_encode/json_decode\n        'metadata' =&gt; 'encrypted:array', // Laravel 11+ encrypted casting\n        'password' =&gt; 'hashed', // Laravel 10+ auto-hashes on set\n    ];\n}\n</code></pre>\n<h3>Model Security</h3>\n<pre><code>final class User extends Authenticatable\n{\n    // Hide sensitive attributes from JSON/API responses\n    protected $hidden = [\n        'password',\n        'remember_token',\n        'two_factor_secret',\n        'two_factor_recovery_codes',\n    ];\n\n    // Append only safe computed attributes\n    protected $appends = ['full_name']; // safe\n    // NEVER append sensitive computed data\n}\n\nfinal class Post extends Model\n{\n    // Global scope to filter soft deleted records\n    use SoftDeletes;\n\n    // Prevent N+1 by restricting lazy loading (optional strict mode)\n    // AppServiceProvider::boot()\n    // Model::preventLazyLoading(!app()-&gt;isProduction());\n}\n</code></pre>\n<h2>CSRF Protection</h2>\n<h3>Default Protection</h3>\n<pre><code>// Laravel CSRF is enabled by default via VerifyCsrfToken middleware\n// app/Http/Kernel.php (protected $middlewareGroups['web'])\n\n// All POST/PUT/PATCH/DELETE forms must include @csrf\n&lt;form method=\"POST\" action=\"/posts\"&gt;\n    @csrf\n    &lt;input type=\"text\" name=\"title\"&gt;\n    &lt;button type=\"submit\"&gt;Create&lt;/button&gt;\n&lt;/form&gt;\n</code></pre>\n<h3>Excluding Routes (Carefully)</h3>\n<pre><code>// app/Http/Middleware/VerifyCsrfToken.php\nclass VerifyCsrfToken extends Middleware\n{\n    // Only exclude routes that have external CSRF protection (webhooks, etc.)\n    protected $except = [\n        'stripe/*', // Stripe webhooks use their own signature verification\n        // Avoid blanket 'api/*' — stateful Sanctum routes need CSRF.\n        // Exclude only specific stateless webhook/endpoint routes.\n    ];\n}\n</code></pre>\n<h3>CSRF with JavaScript</h3>\n<pre><code>&lt;meta name=\"csrf-token\" content=\"{{ csrf_token() }}\"&gt;\n\n&lt;script&gt;\n// Axios example (Laravel ships with Axios)\naxios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector(\n    'meta[name=\"csrf-token\"]'\n).getAttribute('content');\n\n// Fetch example\nfetch('/posts', {\n    method: 'POST',\n    headers: {\n        'X-CSRF-TOKEN': document.querySelector('meta[name=\"csrf-token\"]').getAttribute('content'),\n        'Content-Type': 'application/json',\n    },\n    body: JSON.stringify(data),\n});\n&lt;/script&gt;\n</code></pre>\n<h2>XSS Prevention</h2>\n<h3>Blade Templating Security</h3>\n<pre><code>{{-- SAFE: Auto-escaped by Blade --}}\n{{ $userInput }}\n\n{{-- DANGEROUS: Raw output — NEVER use with user input --}}\n{!! $userInput !!}\n\n{{-- SAFE: Only use {!! !!} with trusted content you control --}}\n{!! $trustedHtmlFromYourServer !!}\n\n{{-- GOOD: Use specific escaping directives --}}\n@js($data) {{-- JSON encode for JavaScript --}}\n@json($data) {{-- JSON encode in templates --}}\n\n{{-- BAD: Direct user input in raw HTML --}}\n&lt;div&gt;{!! $user-&gt;bio !!}&lt;/div&gt; {{-- VULNERABLE if user provides bio --}}\n</code></pre>\n<h3>Safe HTML Handling</h3>\n<pre><code>// When you must allow some HTML, use a whitelist approach\nuse HTMLPurifier; // Requires: composer require ezyang/htmlpurifier\n\npublic function sanitizeHtml(string $dirty): string\n{\n    $config = \\HTMLPurifier_Config::createDefault();\n    $config-&gt;set('HTML.Allowed', 'p,b,i,a[href],ul,ol,li,br');\n    $config-&gt;set('URI.AllowedSchemes', ['http', 'https', 'mailto']);\n    $purifier = new \\HTMLPurifier($config);\n    return $purifier-&gt;purify($dirty);\n}\n\n// In blade:\n&lt;div&gt;{!! $sanitizedContent !!}&lt;/div&gt; {{-- Safe after purification --}}\n</code></pre>\n<h3>JavaScript Context Escaping</h3>\n<pre><code>{{-- SAFE: Blade @js escapes for JavaScript context --}}\n&lt;script&gt;\n    const user = @js($user); // JSON + escaped for JS context\n    const settings = @json($settings); // Direct JSON encode\n&lt;/script&gt;\n\n{{-- DANGEROUS: Manual JSON in JS context --}}\n&lt;script&gt;\n    const user = {{ json_encode($user) }}; // NOT escaped for JS!\n&lt;/script&gt;\n</code></pre>\n<h3>HTTP Headers for XSS Protection</h3>\n<pre><code>// App\\Http\\Middleware\\SecurityHeaders.php\nclass SecurityHeaders\n{\n    public function handle(Request $request, Closure $next): mixed\n    {\n        $response = $next($request);\n\n        $response-&gt;headers-&gt;set('X-Content-Type-Options', 'nosniff');\n        $response-&gt;headers-&gt;set('X-Frame-Options', 'DENY');\n        $response-&gt;headers-&gt;set('X-XSS-Protection', '1; mode=block');\n        $response-&gt;headers-&gt;set('Referrer-Policy', 'strict-origin-when-cross-origin');\n        $response-&gt;headers-&gt;set(\n            'Content-Security-Policy',\n            \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'\"\n        );\n\n        return $response;\n    }\n}\n\n// Register in kernel\nprotected $middleware = [\n    \\App\\Http\\Middleware\\SecurityHeaders::class,\n];\n</code></pre>\n<h2>Input Validation</h2>\n<h3>Form Request Validation</h3>\n<pre><code>final class StorePostRequest extends FormRequest\n{\n    public function authorize(): bool\n    {\n        return $this-&gt;user()?-&gt;can('create', Post::class) ?? false;\n    }\n\n    public function rules(): array\n    {\n        return [\n            'title' =&gt; ['required', 'string', 'max:255'],\n            'content' =&gt; ['required', 'string', 'max:10000'],\n            'image' =&gt; [\n                'required',\n                'image',\n                'mimes:jpg,jpeg,png,gif,webp', // Whitelist specific types\n                'max:2048', // 2MB max\n            ],\n            'tags' =&gt; ['array'],\n            'tags.*' =&gt; ['integer', 'exists:tags,id'],\n        ];\n    }\n\n    public function messages(): array\n    {\n        return [\n            'title.max' =&gt; 'Post title must not exceed 255 characters.',\n            'image.max' =&gt; 'Image must be under 2MB.',\n        ];\n    }\n\n    // Sanitize input after validation\n    public function validated($key = null, $default = null): mixed\n    {\n        $validated = parent::validated();\n        $validated['title'] = strip_tags($validated['title']);\n        return $key ? ($validated[$key] ?? $default) : $validated;\n    }\n}\n</code></pre>\n<h3>Custom Validation Rules</h3>\n<pre><code>// app/Rules/StrongPassword.php\nclass StrongPassword implements Rule\n{\n    public function passes($attribute, $value): bool\n    {\n        return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&amp;#^()_\\-+=])[A-Za-z\\d@$!%*?&amp;#^()_\\-+=]{12,}$/', $value);\n    }\n\n    public function message(): string\n    {\n        return 'The :attribute must be at least 12 characters with uppercase, lowercase, number, and symbol.';\n    }\n}\n\n// app/Rules/NotBlacklistedDomain.php\nclass NotBlacklistedDomain implements Rule\n{\n    private array $blacklisted = ['mailinator.com', 'guerrillamail.com'];\n\n    public function passes($attribute, $value): bool\n    {\n        $domain = substr(strrchr($value, '@'), 1);\n        return !in_array(strtolower($domain), $this-&gt;blacklisted);\n    }\n\n    public function message(): string\n    {\n        return 'Email from disposable domains is not allowed.';\n    }\n}\n</code></pre>\n<h2>API Security</h2>\n<h3>Rate Limiting</h3>\n<pre><code>// App/Providers/RouteServiceProvider\nprotected function configureRateLimiting(): void\n{\n    RateLimiter::for('api', function (Request $request) {\n        return Limit::perMinute(60)-&gt;by($request-&gt;user()?-&gt;id ?: $request-&gt;ip());\n    });\n\n    RateLimiter::for('auth', function (Request $request) {\n        return Limit::perMinute(5)-&gt;by($request-&gt;ip())\n            -&gt;response(function () {\n                return response()-&gt;json([\n                    'message' =&gt; 'Too many login attempts. Try again in 1 minute.',\n                ], 429);\n            });\n    });\n\n    RateLimiter::for('uploads', function (Request $request) {\n        return Limit::perHour(10)-&gt;by($request-&gt;user()?-&gt;id ?? $request-&gt;ip())\n            -&gt;response(function () {\n                return response()-&gt;json([\n                    'message' =&gt; 'Upload limit reached. Try again later.',\n                ], 429);\n            });\n    });\n}\n\n// Route usage\nRoute::middleware(['auth:sanctum', 'throttle:api'])-&gt;group(function () {\n    Route::apiResource('posts', PostController::class);\n});\n\nRoute::post('/login', [AuthController::class, 'login'])\n    -&gt;middleware('throttle:auth');\n</code></pre>\n<h3>API Authentication — Sanctum vs Passport</h3>\n<pre><code>// Sanctum (recommended for most apps — simple, first-party, SPA)\n// config/sanctum.php\n'expiration' =&gt; 60 * 24, // Tokens expire after 24 hours\n'model' =&gt; User::class,\n\n// Issuing scoped tokens\n$token = $user-&gt;createToken('client-name', [\n    'posts:read',\n    'posts:write',\n])-&gt;plainTextToken;\n\n// Middleware scoping\nRoute::middleware('auth:sanctum')-&gt;group(function () {\n    Route::get('/posts', [PostController::class, 'index'])\n        -&gt;middleware('abilities:posts:read');\n\n    Route::post('/posts', [PostController::class, 'store'])\n        -&gt;middleware('abilities:posts:write');\n});\n\n// Passport (OAuth2 — for third-party clients or complex auth flows)\n// Install: composer require laravel/passport\nPassport::tokensExpireIn(now()-&gt;addDays(15));\nPassport::refreshTokensExpireIn(now()-&gt;addDays(30));\nPassport::personalAccessTokensExpireIn(now()-&gt;addMonths(6));\n</code></pre>\n<h3>CORS Configuration</h3>\n<pre><code>// config/cors.php\nreturn [\n    'paths' =&gt; ['api/*', 'sanctum/csrf-cookie'],\n    'allowed_methods' =&gt; ['*'],\n    'allowed_origins' =&gt; explode(',', env('CORS_ALLOWED_ORIGINS', '')), // Whitelist specific origins\n    'allowed_origins_patterns' =&gt; [],\n    'allowed_headers' =&gt; ['*'],\n    'exposed_headers' =&gt; ['X-Total-Count', 'X-Pagination-Page'],\n    'max_age' =&gt; 0,\n    'supports_credentials' =&gt; true, // Required for Sanctum SPA auth\n];\n\n// NEVER: Allow all origins in production unless absolutely necessary\n// 'allowed_origins' =&gt; ['*'], // Only for truly public APIs\n</code></pre>\n<h2>File Upload Security</h2>\n<h3>Validation</h3>\n<pre><code>public function rules(): array\n{\n    return [\n        'document' =&gt; [\n            'required',\n            'file',\n            'mimes:pdf,doc,docx,xls,xlsx', // Whitelist specific MIME types\n            'max:10240', // 10MB\n            'extensions:pdf,doc,docx,xls,xlsx', // Verify extension matches MIME\n        ],\n        'avatar' =&gt; [\n            'nullable',\n            'image', // Ensures it's a valid image\n            'mimes:jpg,jpeg,png,webp',\n            'max:2048',\n            'dimensions:min_width=100,min_height=100,max_width=2000,max_height=2000',\n        ],\n    ];\n}\n</code></pre>\n<h3>Secure Storage</h3>\n<pre><code>// Store sensitive files on the same private disk used to create temporary URLs.\n$path = $request-&gt;file('document')-&gt;store('documents', 's3');\n// Never use the 'public' disk for sensitive documents.\n\n// Use signed URLs for temporary file access\nuse Illuminate\\Support\\Facades\\Storage;\n\npublic function download(Document $document)\n{\n    // Requires route-model binding for Document, a persisted $document-&gt;path,\n    // and a DocumentPolicy::download rule registered with Laravel.\n    // Authorize against the model that owns the file, never a path taken from the request\n    $this-&gt;authorize('download', $document);\n\n    // Generate the temporary signed URL (expires in 15 minutes) only after authorization\n    $url = Storage::disk('s3')-&gt;temporaryUrl($document-&gt;path, now()-&gt;addMinutes(15));\n\n    return redirect($url);\n}\n\n// Storage configuration for cloud with encryption\n// config/filesystems.php\n's3' =&gt; [\n    'driver' =&gt; 's3',\n    'key' =&gt; env('AWS_ACCESS_KEY_ID'),\n    'secret' =&gt; env('AWS_SECRET_ACCESS_KEY'),\n    'region' =&gt; env('AWS_DEFAULT_REGION'),\n    'bucket' =&gt; env('AWS_BUCKET'),\n    'url' =&gt; env('AWS_URL'),\n    'endpoint' =&gt; env('AWS_ENDPOINT'),\n    'use_path_style_endpoint' =&gt; env('AWS_USE_PATH_STYLE_ENDPOINT', false),\n    'throw' =&gt; false,\n    'server_side_encryption' =&gt; 'AES256', // Encrypt at rest\n],\n</code></pre>\n<h2>Dependencies and Secrets</h2>\n<h3>Composer Security</h3>\n<pre><code># Always audit dependencies in CI\ncomposer audit\n\n# Pin major versions in composer.json\n\"laravel/framework\": \"^11.0\",\n\"spatie/laravel-permission\": \"^6.0\"\n\n# Check for abandoned packages\ncomposer why-not\n\n# Keep lock file in version control (it pins exact versions)\n# Run `composer update` deliberately, never in CI/CD\n</code></pre>\n<h3>Secret Management</h3>\n<pre><code># .env file (NEVER commit)\n# .gitignore includes .env by default\n\nAPP_KEY=base64:abc123...\nDB_PASSWORD=secure_password\nSTRIPE_KEY=sk_live_...\nSANCTUM_TOKEN_PREFIX=myapp_\n\n# For production: Use a secret manager\n# Deploy with: env $(aws secretsmanager get-secret-value --secret-id prod/db | jq ...) php artisan serve\n\n# Validate secrets at boot (AppServiceProvider::boot)\n$secrets = ['services.stripe.key', 'services.stripe.webhook_secret'];\nforeach ($secrets as $key) {\n    if (empty(config($key))) {\n        Log::critical(\"Missing secret: {$key}\");\n    }\n}\n</code></pre>\n<h2>Queue Security</h2>\n<pre><code>// Define a named rate limiter (typically in AppServiceProvider::boot())\nRateLimiter::for('payments', fn () =&gt; Limit::perMinute(5));\n</code></pre>\n<pre><code>// Encrypt sensitive job data by implementing the interface\nfinal class ProcessPaymentJob implements ShouldQueue, ShouldBeEncrypted\n{\n    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;\n\n    public function __construct(\n        private readonly string $paymentIntentId, // Public IDs are fine\n        private readonly string $cardFingerprint, // Encrypted via ShouldBeEncrypted\n    ) {}\n\n    public function handle(): void\n    {\n        // Process payment\n    }\n\n    // Limit retries and delay between attempts\n    public function retryUntil(): Carbon\n    {\n        return now()-&gt;addMinutes(5);\n    }\n\n    // Rate limit how many jobs of this type can run\n    public function middleware(): array\n    {\n        return [\n            new RateLimited('payments'),\n        ];\n    }\n}\n</code></pre>\n<h2>Logging Security Events</h2>\n<pre><code>// config/logging.php\n'channels' =&gt; [\n    'security' =&gt; [\n        'driver' =&gt; 'single',\n        'path' =&gt; storage_path('logs/security.log'),\n        'level' =&gt; 'warning',\n    ],\n],\n\n// Audit log helper\nfinal class SecurityLogger\n{\n    public static function log(string $event, array $context = []): void\n    {\n        Log::channel('security')-&gt;warning($event, array_merge([\n            'user_id' =&gt; Auth::id(),\n            'ip' =&gt; request()-&gt;ip(),\n            'user_agent' =&gt; request()-&gt;userAgent(),\n            'url' =&gt; request()-&gt;fullUrl(),\n            'timestamp' =&gt; now()-&gt;toIso8601String(),\n        ], $context));\n    }\n}\n\n// Usage\nSecurityLogger::log('failed_login_attempt', ['email' =&gt; $email]);\nSecurityLogger::log('password_change');\nSecurityLogger::log('role_change', ['target_user' =&gt; $targetId, 'new_role' =&gt; 'admin']);\nSecurityLogger::log('suspicious_activity', ['reason' =&gt; 'multiple_attempts_from_different_ips']);\n</code></pre>\n<h2>Quick Security Checklist</h2>\n<table>\n<thead>\n<tr>\n<th>Check</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>APP_DEBUG=false</code></td>\n<td>Never run with debug enabled in production</td>\n</tr>\n<tr>\n<td><code>APP_KEY</code> set</td>\n<td>Always run <code>php artisan key:generate</code></td>\n</tr>\n<tr>\n<td>HTTPS enforced</td>\n<td>Force HTTPS in production via middleware or proxy</td>\n</tr>\n<tr>\n<td><code>$fillable</code> whitelisted</td>\n<td>Never use <code>$guarded = []</code></td>\n</tr>\n<tr>\n<td>CSRF active</td>\n<td><code>@csrf</code> on all state-changing forms</td>\n</tr>\n<tr>\n<td>Sanctum/Passport configured</td>\n<td>API authentication with token abilities/scopes</td>\n</tr>\n<tr>\n<td>Rate limiting applied</td>\n<td>Throttle API and auth endpoints</td>\n</tr>\n<tr>\n<td>Input validation</td>\n<td>FormRequest with specific rules, never <code>$request-&gt;all()</code></td>\n</tr>\n<tr>\n<td>File upload restrictions</td>\n<td>Validate MIME types, size, dimensions</td>\n</tr>\n<tr>\n<td><code>composer audit</code> in CI</td>\n<td>Check dependencies for known vulnerabilities</td>\n</tr>\n<tr>\n<td><code>password_hash</code> / <code>password_verify</code></td>\n<td>Use Laravel's built-in hashing (bcrypt/Argon2)</td>\n</tr>\n<tr>\n<td>Session regeneration on login</td>\n<td>Call <code>$request-&gt;session()-&gt;regenerate()</code></td>\n</tr>\n<tr>\n<td>Security headers middleware</td>\n<td>CSP, X-Frame-Options, X-Content-Type-Options</td>\n</tr>\n<tr>\n<td>Logged security events</td>\n<td>Audit log for auth failures, role changes, suspicious activity</td>\n</tr>\n<tr>\n<td><code>.env</code> not committed</td>\n<td>Verify <code>.gitignore</code> includes <code>.env</code></td>\n</tr>\n</tbody>\n</table>\n<h2>Related Skills</h2>\n<ul>\n<li><code>laravel-patterns</code> — Laravel architecture, routing, Eloquent, and API patterns</li>\n<li><code>backend-patterns</code> — General backend API and database patterns</li>\n<li><code>laravel-tdd</code> — Laravel testing with PHPUnit and Pest</li>\n</ul>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":26827,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"notes-only","suspicious":0,"notes":14,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:57:29.160941Z","sha256":"1349C584D7C2396A9E60333B8671273E18B2F62B3CD6816BE2F3DB1BCA27D108","sizeBytes":10342},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/laravel-security","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"A292C3C22EB283648C42B68EA2D257E894D1EF305B416E9B70AB7550BEF7CA2D","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T17:04:54.97621Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/laravel-security"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}