Laravel API Security Checklist
Secure your Laravel API endpoints against common vulnerabilities. Covers authentication, input validation, rate limiting, and response security.
Authentication & Authorization
Never roll your own token authentication. Sanctum is ideal for SPA and mobile app APIs. Passport is appropriate for full OAuth2 requirements. Both handle token generation, validation, and revocation securely.
API tokens should have a defined lifetime. For Sanctum, set the expiration in config/sanctum.php. Implement token rotation for long-lived sessions to limit the damage of a compromised token.
Use Laravel Policies and Gates to verify the authenticated user has permission to access the requested resource. Never rely solely on authentication — always check authorization for the specific action.
Use token abilities (Sanctum) or scopes (Passport) to limit what each token can do. A token for reading user profiles should not be able to delete accounts.
Review routes/api.php and remove any unused endpoints. Every registered route is a potential attack surface. Use Route::apiResource() instead of Route::resource() to exclude form-related routes.
Input Validation & Data Handling
Use dedicated FormRequest classes for every endpoint that accepts input. Define strict validation rules including types, lengths, and formats. Never trust client-side validation alone.
API Resources control exactly which fields are returned in responses. This prevents accidentally exposing sensitive fields like passwords, tokens, or internal IDs that exist on your Eloquent models.
Define $fillable or $guarded on every Eloquent model. Never use Model::create($request->all()) — always specify the exact fields: Model::create($request->validated()).
Validate file types, sizes, and MIME types. Use the mimes, mimetypes, and max validation rules. Store uploaded files outside the public directory and serve them through a controller.
If you must use DB::raw(), DB::select(), or whereRaw(), always use parameter binding. Never concatenate user input into SQL strings. Eloquent's query builder handles this automatically for standard operations.
Rate Limiting & Abuse Prevention
Use Laravel's built-in throttle middleware. Define rate limits in RouteServiceProvider using RateLimiter::for(). Apply stricter limits to authentication endpoints (5-10 per minute) and moderate limits to data endpoints (60 per minute).
Login, registration, password reset, and token generation endpoints should have aggressive rate limiting (e.g., 5 attempts per minute) to prevent brute-force and credential stuffing attacks.
When a client exceeds rate limits, return a 429 Too Many Requests response with the Retry-After header. Laravel's throttle middleware does this automatically.
Configure your web server (Nginx/Apache) and PHP to reject oversized request bodies. This prevents denial of service through large payload attacks. Set client_max_body_size in Nginx and post_max_size in PHP.
Never return unbounded result sets. Use Laravel's paginate() method and set a reasonable maximum per_page value. This prevents memory exhaustion and data harvesting.
Response Security & Headers
API error responses in debug mode include full stack traces, file paths, and environment variables. Set APP_DEBUG=false in production and use custom exception handling for clean error responses.
Set allowed_origins in config/cors.php to specific domains, never use the wildcard (*) for authenticated endpoints. Misconfigured CORS allows any website to make API requests on behalf of your users.
Add X-Content-Type-Options: nosniff, Cache-Control: no-store (for sensitive data), and Strict-Transport-Security headers to API responses via middleware.
Use a consistent JSON error format across all endpoints. Never expose internal error messages, database errors, or file paths. Return generic messages with appropriate HTTP status codes.
If an endpoint only handles GET requests, do not register it for POST, PUT, or DELETE. Use specific route methods (Route::get) instead of Route::any or Route::match with unnecessary methods.
Frequently Asked Questions
Should I use Sanctum or Passport for API authentication?
Use Sanctum for SPA authentication, mobile app tokens, and simple API token use cases. Use Passport when you need full OAuth2 support, such as when building an API that third-party developers will consume with authorization codes and client credentials.
How do I prevent API abuse without blocking legitimate users?
Implement tiered rate limiting: strict limits on authentication endpoints (5/minute), moderate limits on write endpoints (30/minute), and generous limits on read endpoints (120/minute). Use per-user rate limiting rather than per-IP to avoid blocking shared networks.
What CORS configuration is secure for a Laravel API?
Set allowed_origins to the specific domains that need access (e.g., your frontend domain). Never use the wildcard (*) for APIs that handle authenticated requests. Set allowed_methods to only the HTTP methods your API uses, and allowed_headers to only the headers you need.
Related Fix Guides
How to Fix an Exposed .env File in Laravel
Your Laravel .env file is publicly accessible, exposing database credentials and API keys. Learn how to block access and secure your secrets.
How to Fix Debug Mode Enabled in Production Laravel
APP_DEBUG=true in production exposes stack traces, environment variables, and database credentials. Learn how to disable it safely.
How to Fix Missing Security Headers in Laravel
Your Laravel app is missing critical security headers like CSP, HSTS, and X-Frame-Options. Learn how to add them with middleware.
Other Checklists
Laravel Production Deployment Security Checklist
A comprehensive security checklist for deploying Laravel applications to production. Covers environment config, server hardening, access control, and monitoring.
Laravel Authentication Security Checklist
Harden your Laravel authentication system against brute-force attacks, session hijacking, and credential theft with this security checklist.
Laravel Pre-Launch Security Checklist
Essential security checks to complete before launching your Laravel application. Covers code review, configuration audit, infrastructure, and monitoring setup.
Automate These Checks with StackShield
Stop running through checklists manually. StackShield continuously monitors your Laravel application for the security issues that matter most.
Start Free Trial