Laravel API Security beginner to advanced
Laravel-এ API নিরাপদ করার জন্য আপনি beginner থেকে advanced পর্যায়ের বিভিন্ন টেকনিক ব্যবহার করতে পারেন। নিচে আমি ধাপে ধাপে ব্যাখ্যা করছি:
✅ Beginner Approaches (Easy & Common)
1. Use Laravel Sanctum (Token Authentication)
-
ছোট বা medium scale API গুলোর জন্য সহজ ও লাইটওয়েট।
-
User login এর পর token issue করে, এবং প্রতিটি request এ token পাঠিয়ে authentication করে।
📌 Install & Setup:
📌 User model-এ: HasApiTokens trait ব্যবহার করুন।
📌 Token issue:
📌 Protect Route:
2. Rate Limiting (Throttle Requests)
-
API abuse কমাতে সহায়তা করে।
📌 Route-এ middleware:
➜ ১ মিনিটে সর্বোচ্চ ৬০টি request.
3. Validation & Input Sanitization
-
Input validate না করলে attacker XSS, SQL Injection চেষ্টা করতে পারে।
📌 Controller/Request Class:
4. CORS Middleware Configuration
-
অন্য domain থেকে অনিরাপদ API call বন্ধ করতে CORS properly configure করতে হবে।
📌 config/cors.php ফাইলে origin, method, credentials ইত্যাদি সেট করুন।
🔒 Advanced Approaches (For Production APIs)
5. Use Laravel Passport (OAuth2)
-
Complex application বা multiple client system (mobile, frontend app) এর জন্য।
📌 composer require laravel/passport
📌 Token issue, refresh, scopes, client credentials — সবই configure করা যায়।
6. JWT (JSON Web Token) Authentication
-
Stateless authentication system।
-
Package:
tymon/jwt-auth
📌 Install:
📌 Login & Token:
📌 Middleware:
7. Encrypt Sensitive Data
-
যেমন user token, payment info ইত্যাদি encrypt করে রাখুন।
8. Use HTTPS (SSL)
-
SSL ছাড়া sensitive data send করলে sniffing হতে পারে।
📌 .env ফাইলে:
📌 \AppServiceProvider::boot() এ force HTTPS redirect:
9. Scope-based Authorization
-
Different user role অনুযায়ী API access control।
10. API Firewall / WAF Integration
-
Cloudflare, AWS WAF ইত্যাদি ব্যবহার করে IP blacklist, bot detection।
11. Log API Requests Securely
-
কিন্তু sensitive info (password, token) log করবেন না।
📌 Use Laravel’s built-in logging + masking sensitive fields.
12. Content Security Policy (CSP), CSRF (for web), XSS Prevention
-
API র জন্য XSS কম হলেও frontend integrated হলে খেয়াল রাখতে হবে।
🧪 Bonus: Security Checklist
-
✅ Token-based authentication (Sanctum / Passport / JWT)
-
✅ Input validation everywhere
-
✅ CORS configured properly
-
✅ API rate limiting (throttle)
-
✅ HTTPS enabled
-
✅ Sensitive data encryption
-
✅ Proper logging (no sensitive info)
🔚 শেষ কথা:
Beginners এর জন্য Sanctum + Throttle + Validation + CORS হলো best start।
Advanced users এর জন্য JWT বা Passport, rate limit, encryption, logging, WAF integration essential।
Enterprise-level Laravel বা যেকোনো API-ভিত্তিক অ্যাপ্লিকেশনে security দেওয়া হয় multi-layered approach-এ, অর্থাৎ একাধিক স্তরে সুরক্ষা নিশ্চিত করে। নিচে দেওয়া হলো enterprise-grade API security techniques গুলো:
🛡️ 1. Authentication System (OAuth2, JWT, SSO)
✅ OAuth2 (Laravel Passport / Keycloak Integration)
-
Use case: third-party integrations, mobile apps, microservices.
-
Support for: access tokens, refresh tokens, scopes, client credentials.
✅ SSO (Single Sign-On)
-
Common for enterprise ecosystems (e.g. Microsoft Azure AD, Okta, LDAP).
-
ব্যবহারকারী একবার লগইন করলেই সমস্ত সিস্টেমে অটো লগইন।
✅ JWT with Custom Claims
-
Stateless token, scalable in microservices.
-
Custom claims add করে user roles, permissions encode করে দেয়।
🔐 2. Role-based & Permission-based Access Control (RBAC / ACL)
-
Users → Roles → Permissions.
-
Example:
-
Laravel-এ
spatie/laravel-permissionpackage widely used for this.
🌐 3. Rate Limiting & Abuse Prevention
-
Redis-backed
ThrottleMiddlewareorAPI Gatewaylevel throttling. -
Example:
-
Complex systems use:
-
Per-user, Per-IP, or Per-endpoint rate limits.
-
ReCAPTCHA / Bot protection for public endpoints.
-
🧱 4. API Gateway Layer (e.g., Kong, AWS API Gateway, Azure API Management)
-
API gateway add করে:
-
Rate limiting
-
IP whitelisting / blacklisting
-
Auth token validation
-
Caching & request shaping
-
Threat protection
-
Laravel sits behind this gateway.
🔍 5. Input Validation + Payload Sanitization
-
Every request must be validated using Laravel’s
FormRequest. -
Prevents:
-
SQL Injection
-
XSS attacks
-
Mass assignment vulnerabilities
-
🔒 6. HTTPS (SSL/TLS) Enforcement
-
SSL enforced by default.
-
Laravel-level redirect via:
-
HSTS headers added for strict transport security.
📦 7. Data Encryption (at Rest and in Transit)
-
Use Laravel’s encryption (Crypt facade) for sensitive fields (e.g., SSN, credit card).
-
Database-level encryption (column-level, e.g., AES-256)
-
Filesystem-level encryption for backups
🔍 8. Logging, Monitoring, and Auditing
-
Every request, response, and login attempt is logged with:
-
IP address
-
User agent
-
Endpoint
-
User ID
-
-
Tools: Laravel Telescope, Sentry, ELK Stack, Datadog, New Relic
-
Audit trail with models like:
🛡️ 9. WAF (Web Application Firewall)
-
Enterprise systems integrate WAFs like:
-
Cloudflare WAF
-
AWS WAF
-
Azure Front Door
-
-
Protects from:
-
OWASP Top 10 threats (SQLi, XSS, CSRF, etc.)
-
DDoS attacks
-
🌐 10. CORS Policy Enforcement
-
Set very specific
allowed_origins, methods, and headers incors.php.
🧾 11. Versioned APIs & Deprecated Endpoint Handling
-
Separate routes per version:
-
Deprecation warnings, sunset headers used:
🧠 12. Zero Trust Architecture
-
Every API request is treated as untrusted, even from internal services.
-
Validate each:
-
Request source (via signed headers or API keys)
-
User identity and access rights
-
Payload structure
-
🚨 13. Security Headers
Laravel middleware level এ নিচের headers গুলো enforce করে:
Can be added via helmet in Node proxy or with Laravel middleware.
📦 Bonus: API Key Management for Third-party Integrations
-
Allow API access via unique API keys (stored securely in DB).
-
Allow/revoke specific keys.
-
Track usage logs for each key.
✅ Enterprise API Security Checklist
| Security Layer | Description | Tool/Package |
|---|---|---|
| Authentication | OAuth2, SSO, JWT | Passport, Keycloak |
| Authorization | RBAC, Scopes | spatie/permission |
| Rate Limit | Prevent abuse | Throttle, Redis |
| Input Sanitation | Prevent injection | FormRequest |
| HTTPS | Encrypted transport | SSL, forceScheme |
| Data Encryption | Sensitive data | Crypt, DB Encryption |
| Audit Logging | Request tracking | Telescope, Sentry |
| API Gateway | Security at edge | Kong, AWS API Gateway |
| WAF | Block threats | Cloudflare, AWS WAF |
| Header Protection | Prevent exploits | Middleware |
| CORS | Cross-domain control | config/cors.php |
| Versioning | v1, v2 separation | Route groups |
==================================================
CORS Middleware Configuration (Credentials সহ)
Laravel-এ CORS কনফিগারেশনে supports_credentials সেটিং যোগ করতে নিচের ধাপগুলো অনুসরণ করুন:
1. config/cors.php ফাইল এডিট করুন:
<?php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
// নির্দিষ্ট ডোমেইন দিন (সব ডোমেইন দেয়ার জন্য ['*'] ব্যবহার করবেন না credentials সত্য হলে)
'allowed_origins' => [
'http://localhost:3000',
'https://yourfrontenddomain.com'
],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
// Credentials সাপোর্ট করতে true সেট করুন
'supports_credentials' => true,
];2. Middleware এ Credentials সেটআপ:
আপনার API রেস্পন্সে প্রয়োজনীয় হেডার যোগ করতে:
// app/Http/Middleware/CorsMiddleware.php (যদি কাস্টম middleware থাকে) public function handle($request, Closure $next) { $response = $next($request); $response->headers->set('Access-Control-Allow-Credentials', 'true'); $response->headers->set('Access-Control-Allow-Origin', config('cors.allowed_origins')); $response->headers->set('Access-Control-Allow-Methods', implode(',', config('cors.allowed_methods'))); $response->headers->set('Access-Control-Allow-Headers', implode(',', config('cors.allowed_headers'))); return $response; }
3. ফ্রন্টএন্ড থেকে API কল করার সময়:
Axios বা Fetch API ব্যবহার করার সময় credentials ইনক্লুড করুন:
// Axios এর উদাহরণ axios.get('https://yourapi.com/api/user', { withCredentials: true }); // Fetch API এর উদাহরণ fetch('https://yourapi.com/api/user', { credentials: 'include' });
গুরুত্বপূর্ণ নোট:
supports_credentialstrue করলেallowed_originsএ'*'ব্যবহার করা যাবে না, স্পেসিফিক ডোমেইন দিতে হবেসেশন কুকিজ বা অথেন্টিকেশন টোকেন পাঠানোর জন্য এটি জরুরী
প্রোডাকশন环境中 সবসময় নির্দিষ্ট ডোমেইন white-list করুন
Sanctum বা Passport ব্যবহার করলে এটি বিশেষভাবে প্রয়োজন
এই কনফিগারেশনটি API কে সুরক্ষিতভাবে ক্রস-অরিজিন রিকোয়েস্ট গ্রহণ করতে সাহায্য করবে, বিশেষ করে যখন ফ্রন্টএন্ড এবং ব্যাকএন্ড আলাদা ডোমেইনে থাকে।
No comments