laravel-security
Laravel security best practices for authn/authz, validation, CSRF, mass assignment, file uploads, secrets, rate limiting, and secure deployment.
About this skill
This skill equips AI agents with a comprehensive understanding of Laravel security best practices, enabling them to generate, review, and harden Laravel applications against common vulnerabilities. It covers crucial aspects such as implementing secure authentication and authorization mechanisms, robust input validation, protection against Cross-Site Request Forgery (CSRF) and mass assignment, safe handling of file uploads, secure management of sensitive information and environment secrets, effective rate limiting strategies, and guidelines for secure production deployments. By leveraging this skill, an AI agent can ensure that Laravel code adheres to high security standards, providing developers with reliable and protected applications.
Best use case
Developers can use this skill via an AI agent for: - Developing new Laravel features requiring robust security implementations. - Auditing existing Laravel codebases for potential vulnerabilities and suggesting fixes. - Refactoring Laravel applications to improve their overall security posture. - Configuring and hardening Laravel deployments for enhanced protection against attacks.
Laravel security best practices for authn/authz, validation, CSRF, mass assignment, file uploads, secrets, rate limiting, and secure deployment.
The AI agent will provide secure, robust Laravel code snippets, architectural recommendations, or security audit reports. It will identify potential vulnerabilities and suggest best-practice solutions, helping to build or refactor Laravel applications with a strong security foundation.
Practical example
Example input
I'm building a new user registration and login system in Laravel. Can you help me implement it securely, covering common vulnerabilities like mass assignment and ensuring strong password handling? Also, provide guidance on securing file uploads for user avatars.
Example output
```json
{
"explanation": "Here's a secure approach for your Laravel user registration, login, and avatar upload system, adhering to best practices:",
"registration_recommendations": [
"Always use `Hash::make()` for password hashing. Never store plain passwords.",
"Implement form request validation to sanitize and validate all input fields (`name`, `email`, `password`).",
"Guard against mass assignment by using `$fillable` or `$guarded` in your `User` model. For example: `protected $fillable = ['name', 'email', 'password'];`",
"Consider using a unique email constraint to prevent duplicate registrations."
],
"login_recommendations": [
"Utilize Laravel's built-in `Auth::attempt()` method for authentication.",
"Implement rate limiting on the login route to prevent brute-force attacks.",
"Consider adding two-factor authentication for enhanced security."
],
"file_upload_security": [
"Use Laravel's `Storage` facade for file uploads. Store files outside the public directory if possible.",
"Validate file types, sizes, and dimensions (e.g., `mimes:jpeg,png,jpg,gif|max:2048` for avatars).",
"Sanitize filenames to prevent path traversal or execution vulnerabilities.",
"Serve user-uploaded files via a secure route that performs authorization checks if necessary."
],
"code_example_registration_controller": "```php\nuse App\\Models\\User;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Support\\Facades\\Hash;\nuse Illuminate\\Validation\\Rules\\Password;\n\nclass RegisterController extends Controller\n{\n public function register(Request $request)\n {\n $request->validate([\n 'name' => ['required', 'string', 'max:255'],\n 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],\n 'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->symbols()->uncompromised()],\n ]);\n\n $user = User::create([\n 'name' => $request->name,\n 'email' => $request->email,\n 'password' => Hash::make($request->password),\n ]);\n\n auth()->login($user);\n\n return redirect('/dashboard');\n }\n}\n```",
"code_example_avatar_upload_controller": "```php\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Support\\Facades\\Storage;\n\nclass ProfileController extends Controller\n{\n public function updateAvatar(Request $request)\n {\n $request->validate([\n 'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);\n\n $path = $request->file('avatar')->store('avatars', 'public'); // Store in 'storage/app/public/avatars'\n auth()->user()->update(['avatar_path' => $path]);\n\n return back()->with('success', 'Avatar updated successfully!');\n }\n}\n```",
"further_actions": "Remember to run `php artisan storage:link` if storing files in `storage/app/public` and serving them via the web."
}
```When to use this skill
- - When implementing authentication or authorization features in a Laravel application. - When processing user input, form submissions, or handling file uploads. - When creating new API endpoints or defining sensitive routes. - When managing sensitive configuration, API keys, or environment variables. - When preparing a Laravel application for production deployment or reviewing its security hardening.
When not to use this skill
- - When working with non-Laravel PHP frameworks or other programming languages, as the advice is Laravel-specific. - When the primary task is not related to security (e.g., pure UI design, general database modeling without security implications). - For very simple, non-production scripts where security is not a critical concern.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/laravel-security/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How laravel-security Compares
| Feature / Agent | laravel-security | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Laravel security best practices for authn/authz, validation, CSRF, mass assignment, file uploads, secrets, rate limiting, and secure deployment.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
AI Agents for Startups
Explore AI agent skills for startup validation, product research, growth experiments, documentation, and fast execution with small teams.
SKILL.md Source
# Laravel Güvenlik En İyi Uygulamaları
Laravel uygulamalarını yaygın güvenlik açıklarına karşı korumak için kapsamlı güvenlik rehberi.
## Ne Zaman Aktif Edilir
- Kimlik doğrulama veya yetkilendirme ekleme
- Kullanıcı girişi ve dosya yüklemelerini işleme
- Yeni API endpoint'leri oluşturma
- Gizli bilgileri ve ortam ayarlarını yönetme
- Production deployment'ları sertleştirme
## Nasıl Çalışır
- Middleware temel korumalar sağlar (CSRF için `VerifyCsrfToken`, güvenlik başlıkları için `SecurityHeaders`).
- Guard'lar ve policy'ler erişim kontrolünü zorlar (`auth:sanctum`, `$this->authorize`, policy middleware).
- Form Request'ler servislere ulaşmadan önce girişi doğrular ve şekillendirir (`UploadInvoiceRequest`).
- Rate limiting, auth kontrolleri ile birlikte kötüye kullanım koruması ekler (`RateLimiter::for('login')`).
- Veri güvenliği encrypted cast'lerden, mass-assignment korumalarından ve signed route'lardan gelir (`URL::temporarySignedRoute` + `signed` middleware).
## Temel Güvenlik Ayarları
- Production'da `APP_DEBUG=false`
- `APP_KEY` ayarlanmalı ve tehlikeye girdiğinde döndürülmelidir
- `SESSION_SECURE_COOKIE=true` ve `SESSION_SAME_SITE=lax` ayarlayın (veya hassas uygulamalar için `strict`)
- Doğru HTTPS algılama için güvenilir proxy'leri yapılandırın
## Session ve Cookie Sertleştirme
- JavaScript erişimini önlemek için `SESSION_HTTP_ONLY=true` ayarlayın
- Yüksek riskli akışlar için `SESSION_SAME_SITE=strict` kullanın
- Login ve ayrıcalık değişikliklerinde session'ları yeniden oluşturun
## Kimlik Doğrulama ve Token'lar
- API kimlik doğrulama için Laravel Sanctum veya Passport kullanın
- Hassas veriler için yenileme akışları ile kısa ömürlü token'ları tercih edin
- Logout ve tehlikeye girmiş hesaplarda token'ları iptal edin
Örnek route koruması:
```php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->get('/me', function (Request $request) {
return $request->user();
});
```
## Parola Güvenliği
- `Hash::make()` ile parolaları hash'leyin ve asla düz metin saklamayın
- Sıfırlama akışları için Laravel'in password broker'ını kullanın
```php
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
$validated = $request->validate([
'password' => ['required', 'string', Password::min(12)->letters()->mixedCase()->numbers()->symbols()],
]);
$user->update(['password' => Hash::make($validated['password'])]);
```
## Yetkilendirme: Policy'ler ve Gate'ler
- Model seviyesi yetkilendirme için policy'leri kullanın
- Controller'larda ve servislerde yetkilendirmeyi zorlayın
```php
$this->authorize('update', $project);
```
Route seviyesi zorlama için policy middleware kullanın:
```php
use Illuminate\Support\Facades\Route;
Route::put('/projects/{project}', [ProjectController::class, 'update'])
->middleware(['auth:sanctum', 'can:update,project']);
```
## Validation ve Veri Temizleme
- Her zaman Form Request'ler ile girişleri doğrulayın
- Sıkı validation kuralları ve tip kontrolleri kullanın
- Türetilmiş alanlar için request payload'larına asla güvenmeyin
## Mass Assignment Koruması
- `$fillable` veya `$guarded` kullanın ve `Model::unguard()` kullanmaktan kaçının
- DTO'ları veya açık attribute mapping'i tercih edin
## SQL Injection Önleme
- Eloquent veya query builder parametre binding kullanın
- Kesinlikle gerekli olmadıkça raw SQL kullanmaktan kaçının
```php
DB::select('select * from users where email = ?', [$email]);
```
## XSS Önleme
- Blade varsayılan olarak çıktıyı escape eder (`{{ }}`)
- `{!! !!}` sadece güvenilir, temizlenmiş HTML için kullanın
- Zengin metni özel bir kütüphane ile temizleyin
## CSRF Koruması
- `VerifyCsrfToken` middleware'ini etkin tutun
- Formlara `@csrf` ekleyin ve SPA istekleri için XSRF token'ları gönderin
Sanctum ile SPA kimlik doğrulaması için, stateful isteklerin yapılandırıldığından emin olun:
```php
// config/sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost')),
```
## Dosya Yükleme Güvenliği
- Dosya boyutunu, MIME tipini ve uzantısını doğrulayın
- Mümkün olduğunda yüklemeleri public path dışında saklayın
- Gerekirse dosyaları malware için tarayın
```php
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'],
];
}
}
```
```php
$path = $request->file('invoice')->store(
'invoices',
config('filesystems.private_disk', 'local') // bunu public olmayan bir disk'e ayarlayın
);
```
## Rate Limiting
- Auth ve yazma endpoint'lerinde `throttle` middleware'i uygulayın
- Login, password reset ve OTP için daha sıkı limitler kullanın
```php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
RateLimiter::for('login', function (Request $request) {
return [
Limit::perMinute(5)->by($request->ip()),
Limit::perMinute(5)->by(strtolower((string) $request->input('email'))),
];
});
```
## Gizli Bilgiler ve Kimlik Bilgileri
- Gizli bilgileri asla kaynak kontrolüne commit etmeyin
- Ortam değişkenlerini ve gizli yöneticileri kullanın
- Maruz kalma sonrası anahtarları döndürün ve session'ları geçersiz kılın
## Şifreli Attribute'lar
Bekleyen hassas sütunlar için encrypted cast'leri kullanın.
```php
protected $casts = [
'api_token' => 'encrypted',
];
```
## Güvenlik Başlıkları
- Uygun yerlerde CSP, HSTS ve frame koruması ekleyin
- HTTPS yönlendirmelerini zorlamak için güvenilir proxy yapılandırması kullanın
Başlıkları ayarlamak için örnek middleware:
```php
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class SecurityHeaders
{
public function handle(Request $request, \Closure $next): Response
{
$response = $next($request);
$response->headers->add([
'Content-Security-Policy' => "default-src 'self'",
'Strict-Transport-Security' => 'max-age=31536000', // tüm subdomain'ler HTTPS olduğunda includeSubDomains/preload ekleyin
'X-Frame-Options' => 'DENY',
'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'no-referrer',
]);
return $response;
}
}
```
## CORS ve API Erişimi
- `config/cors.php`'de origin'leri kısıtlayın
- Kimlik doğrulamalı route'lar için wildcard origin'lerden kaçının
```php
// config/cors.php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
'allowed_origins' => ['https://app.example.com'],
'allowed_headers' => [
'Content-Type',
'Authorization',
'X-Requested-With',
'X-XSRF-TOKEN',
'X-CSRF-TOKEN',
],
'supports_credentials' => true,
];
```
## Loglama ve PII
- Parolaları, token'ları veya tam kart verilerini asla loglamayın
- Yapılandırılmış loglarda hassas alanları redakte edin
```php
use Illuminate\Support\Facades\Log;
Log::info('User updated profile', [
'user_id' => $user->id,
'email' => '[REDACTED]',
'token' => '[REDACTED]',
]);
```
## Bağımlılık Güvenliği
- Düzenli olarak `composer audit` çalıştırın
- Bağımlılıkları dikkatle sabitleyin ve CVE'lerde hızlıca güncelleyin
## Signed URL'ler
Geçici, kurcalamaya dayanıklı bağlantılar için signed route'ları kullanın.
```php
use Illuminate\Support\Facades\URL;
$url = URL::temporarySignedRoute(
'downloads.invoice',
now()->addMinutes(15),
['invoice' => $invoice->id]
);
```
```php
use Illuminate\Support\Facades\Route;
Route::get('/invoices/{invoice}/download', [InvoiceController::class, 'download'])
->name('downloads.invoice')
->middleware('signed');
```Related Skills
laravel-plugin-discovery
Discover and evaluate Laravel packages via LaraPlugins.io MCP. Use when the user wants to find plugins, check package health, or assess Laravel/PHP compatibility.
laravel-verification
Verification loop for Laravel projects: env checks, linting, static analysis, tests with coverage, security scans, and deployment readiness.
laravel-tdd
Test-driven development for Laravel with PHPUnit and Pest, factories, database testing, fakes, and coverage targets.
laravel-patterns
Laravel architecture patterns, routing/controllers, Eloquent ORM, service layers, queues, events, caching, and API resources for production apps.
springboot-security
Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.
django-security
Django security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations.
workspace-surface-audit
Audit the active repo, MCP servers, plugins, connectors, env surfaces, and harness setup, then recommend the highest-value ECC-native skills, hooks, agents, and operator workflows. Use when the user wants help setting up Claude Code or understanding what capabilities are actually available in their environment.
safety-guard
Use this skill to prevent destructive operations when working on production systems or running agents autonomously.
repo-scan
Cross-stack source code asset audit — classifies every file, detects embedded third-party libraries, and delivers actionable four-level verdicts per module with interactive HTML reports.
project-flow-ops
Operate execution flow across GitHub and Linear by triaging issues and pull requests, linking active work, and keeping GitHub public-facing while Linear remains the internal execution layer. Use when the user wants backlog control, PR triage, or GitHub-to-Linear coordination.
manim-video
Build reusable Manim explainers for technical concepts, graphs, system diagrams, and product walkthroughs, then hand off to the wider ECC video stack if needed. Use when the user wants a clean animated explainer rather than a generic talking-head script.
design-system
Use this skill to generate or audit design systems, check visual consistency, and review PRs that touch styling.