Off the back of this article, there could be some potential improvements to make the setup a bit more robust. Instead of copying classes manually into the Lumen’s middleware, it may be best to pull packages from composer and sub-class Laravel’s
ThrottleRequests
class – part of Laravel’s Illuminate Routing library – to avoid missing any potential changes/features in the future.
This process can be done in the following steps:
- Add the Illuminate Routing library via Composer
- Create a sub-classed ThrottleRequests middleware class
- Add the middleware class to the bootstrap
- Implement middleware into the routes
Add the Illuminate Routing library via Composer
Add Laravel’s Illuminate Routing library to your project by running the following command within your root Lumen directory:
- composer require illuminate/routing
Create a sub-classed ThrottleRequests middleware class
Instead of modifying core libraries or copying it into your project, simply create your own middleware class (in this example it was arbitrarily named
RateLimits
) to sub-class the existing
ThrottleRequests
class from the Illumincate Routing library and implement the fingerprinting function within your class.
Within your `app/Http/Middleware` folder create a new middleware class that extends
\Illuminate\Routing\Middleware\ThrottleRequests
. The key is to implement the
resolveRequestSignature
function to define how we want to fingerprint each request.
- <?php
-
- namespace App\Http\Middleware;
-
- use Closure;
-
- class RateLimits extends \Illuminate\Routing\Middleware\ThrottleRequests
- {
- protected function resolveRequestSignature($request)
- {
- $request->method(),
- $request->root(),
- $request->path(),
- $request->ip(),
- $request->query('access_token')
- ]
- ));
-
- return $request->fingerprint();
- }
-
- }
Add the middleware class to the bootstrap
Once your middleware class is created. Activate the middleware via your `bootstrap/app.php` file by adding:
- $app->routeMiddleware([
- 'throttle' => App\Http\Middleware\RateLimits::class
- ]);
Implement middleware into the routes
Use your middleware class in your routes. In the following example we are allowing 2 requests every minute for the “myroute” endpoint.
- $router->get('/myroute', ['middleware' => ['throttle:2,1'], function () use ($router) {
- //do things
- }]);
All steps should now be completed for the Throttling middleware to be activated. If the route is refreshed 3 times very quickly (i.e. within a minute) a 429 HTTP Error response should be returned. In development mode you should see: