Laravel 10: Unable to Use Custom Middleware for Rate Limiting with Passport Authentication
I'm optimizing some code but I'm working on a project and hit a roadblock... I'm working on a project and hit a roadblock. I'm working on a Laravel 10 application where I've implemented Passport for API authentication. I've created a custom middleware to handle rate limiting for specific routes, but it doesn’t seem to be working as expected. When I send multiple requests in a short time frame, I still receive responses without hitting the limit, which should return a 429 Too Many Requests status. Here’s what I’ve done so far: I created a middleware called `RateLimitMiddleware`: ```php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Cache; class RateLimitMiddleware { public function handle($request, Closure $next, $maxAttempts = 5, $decayMinutes = 1) { $key = 'rate_limit:' . $request->user()->id; $attempts = Cache::get($key, 0); if ($attempts >= $maxAttempts) { return response()->json(['message' => 'Too many requests.'], 429); } Cache::put($key, $attempts + 1, $decayMinutes * 60); return $next($request); } } ``` Next, I registered this middleware in `app/Http/Kernel.php`: ```php protected $routeMiddleware = [ // other middlewares 'rate.limit' => \App\Http\Middleware\RateLimitMiddleware::class, ]; ``` Then, I applied it to a route in my `api.php`: ```php Route::middleware(['auth:api', 'rate.limit'])->get('/user', function (Request $request) { return $request->user(); }); ``` Despite this, when I make rapid requests to the `/user` endpoint, I don’t see any rate limiting in action. I even tried clearing the cache with `php artisan cache:clear`, but it didn’t help. I also checked if the user is authenticated properly and that the middleware is indeed being triggered. The requests are authenticated, and I can see that the middleware is running because I added a log statement, which prints out each request's attempt count. However, it seems like the cache isn’t persisting the values as expected. Is there something I’m missing in the configuration, or is there a better way to implement rate limiting with Passport? Any insights would be greatly appreciated! This is for a REST API running on CentOS. I'm working with Php in a Docker container on Windows 11. Any ideas what could be causing this?