Laravel API exclude 1 ip address from rate limiting
Asked Answered
T

1

7

On a Laravel API I've set rate limits using the default middleware for throttling;

Route::group(['prefix' => 'products'], function() {
    Route::get('/', ['as' => 'products.index', 'uses' => 'CustomerProductController@index'])->middleware('throttle:60,1');
    Route::get('/{product}', ['as' => 'products.show', 'uses' => 'CustomerProductController@show'])->middleware('throttle:50,1');
});

Now I need to make my own middleware to exclude 1 ip address from throttling. But somehow I can only find suggestions on doing things the other way around eg. throttling a group of ip addresses.

Can someone give me a nudge in the right direction?

Tilford answered 17/6, 2020 at 8:18 Comment(0)
R
20

Here's a short overview of what I would do.

Step 1

Create a new middleware i.e. ThrottleRequestsWithIp

php artisan make:middleware ThrottleRequestsWithIp

Step 2

Let it extend the original throttle middleware class \Illuminate\Routing\Middleware\ThrottleRequests.

If you want to take a look at the original framework middleware you can find it under /vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php

Overwrite the handle method to check for the IP address and call the parent method if it's not found.

This is how your App\Http\Middleware\ThrottleRequestsWithIp could look like

<?php

namespace App\Http\Middleware;

use Closure;

class ThrottleRequestsWithIp extends \Illuminate\Routing\Middleware\ThrottleRequests
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
    {
        if($request->ip() === "192.168.10.2") 
            return $next($request);

        return parent::handle($request, $next, $maxAttempts, $decayMinutes, $prefix);
    }
}

Step 3

Register your new middleware in Kernel.php, for example

'throttleIp' => \App\Http\Middleware\ThrottleRequestsWithIp::class

Step 4

Use it in your routes like this

Route::get('/', [
    'as' => 'products.index', 
    'uses' => 'CustomerProductController@index'
])->middleware('throttleIp:60,1');
Ranch answered 17/6, 2020 at 8:32 Comment(1)
It definitely did help. Thanks a lot.Tilford

© 2022 - 2024 — McMap. All rights reserved.