Header Ads

Header ADS

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:

bash
composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate

📌 User model-এ: HasApiTokens trait ব্যবহার করুন।

php
use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; }

📌 Token issue:

php
$user = User::where('email', $request->email)->first(); $token = $user->createToken('auth_token')->plainTextToken;

📌 Protect Route:

php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); });

2. Rate Limiting (Throttle Requests)

  • API abuse কমাতে সহায়তা করে।

📌 Route-এ middleware:

php
Route::middleware('throttle:60,1')->group(function () { Route::get('/api/posts', [PostController::class, 'index']); });

➜ ১ মিনিটে সর্বোচ্চ ৬০টি request.


3. Validation & Input Sanitization

  • Input validate না করলে attacker XSS, SQL Injection চেষ্টা করতে পারে।

📌 Controller/Request Class:

php
$request->validate([ 'email' => 'required|email', 'password' => 'required|min:6', ]);

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:

bash
composer require tymon/jwt-auth php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" php artisan jwt:secret

📌 Login & Token:

php
$token = JWTAuth::attempt($credentials);

📌 Middleware:

php
Route::middleware(['jwt.auth'])->group(function () { Route::get('/profile', [ProfileController::class, 'index']); });

7. Encrypt Sensitive Data

  • যেমন user token, payment info ইত্যাদি encrypt করে রাখুন।

php
use Illuminate\Support\Facades\Crypt; $encrypted = Crypt::encryptString('secret_data'); $decrypted = Crypt::decryptString($encrypted);

8. Use HTTPS (SSL)

  • SSL ছাড়া sensitive data send করলে sniffing হতে পারে।

📌 .env ফাইলে:

ini
APP_URL=https://yourdomain.com

📌 \AppServiceProvider::boot() এ force HTTPS redirect:

php
if(env('APP_ENV') === 'production') { \URL::forceScheme('https'); }

9. Scope-based Authorization

  • Different user role অনুযায়ী API access control।

php
$user->tokenCan('create-posts');

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:

php
Gate::define('edit-post', function ($user, $post) { return $user->id === $post->user_id || $user->hasRole('admin'); });
  • Laravel-এ spatie/laravel-permission package widely used for this.


🌐 3. Rate Limiting & Abuse Prevention

  • Redis-backed ThrottleMiddleware or API Gateway level throttling.

  • Example:

php
Route::middleware(['throttle:api'])->group(function () { Route::get('/data', 'DataController@index'); });
  • 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

php
public function rules() { return [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', ]; }

🔒 6. HTTPS (SSL/TLS) Enforcement

  • SSL enforced by default.

  • Laravel-level redirect via:

php
\URL::forceScheme('https');
  • 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:

bash
composer require spatie/laravel-activitylog

🛡️ 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 in cors.php.

php
'paths' => ['api/*'], 'allowed_origins' => ['https://your-app.com'], 'allowed_methods' => ['GET', 'POST'],

🧾 11. Versioned APIs & Deprecated Endpoint Handling

  • Separate routes per version:

php
Route::prefix('v1')->group(...) Route::prefix('v2')->group(...)
  • Deprecation warnings, sunset headers used:

http
Sunset: Sat, 01 Dec 2025 00:00:00 GMT

🧠 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 করে:

php
Content-Security-Policy X-Content-Type-Options: nosniff X-Frame-Options: DENY Strict-Transport-Security Referrer-Policy

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 LayerDescriptionTool/Package
AuthenticationOAuth2, SSO, JWTPassport, Keycloak
AuthorizationRBAC, Scopesspatie/permission
Rate LimitPrevent abuseThrottle, Redis
Input SanitationPrevent injectionFormRequest
HTTPSEncrypted transportSSL, forceScheme
Data EncryptionSensitive dataCrypt, DB Encryption
Audit LoggingRequest trackingTelescope, Sentry
API GatewaySecurity at edgeKong, AWS API Gateway
WAFBlock threatsCloudflare, AWS WAF
Header ProtectionPrevent exploitsMiddleware
CORSCross-domain controlconfig/cors.php
Versioningv1, v2 separationRoute groups



No comments

Theme images by fpm. Powered by Blogger.