【问题标题】:Laravel API exclude 1 ip address from rate limitingLaravel API 从速率限制中排除 1 个 IP 地址
【发布时间】:2020-10-07 00:08:27
【问题描述】:

在 Laravel API 上,我使用默认中间件设置了速率限制;

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');
});

现在我需要制作自己的中间件来排除 1 个 IP 地址的限制。 但不知何故,我只能找到以相反方式做事的建议,例如。限制一组 IP 地址。

有人可以在正确的方向上轻推我吗?

【问题讨论】:

    标签: php laravel middleware throttling


    【解决方案1】:

    以下是我将要做什么的简短概述。

    第 1 步

    创建一个新的中间件,即ThrottleRequestsWithIp

    php artisan make:middleware ThrottleRequestsWithIp
    

    第 2 步

    让它扩展原来的throttle中间件类\Illuminate\Routing\Middleware\ThrottleRequests。

    如果你想看看原来的框架中间件你可以在/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php下找到它

    覆盖handle方法以检查IP地址,如果找不到则调用父方法。

    这就是你的App\Http\Middleware\ThrottleRequestsWithIp 的样子

    <?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);
        }
    }
    

    第 3 步

    例如在 Kernel.php 中注册你的新中间件

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

    第 4 步

    像这样在你的路线中使用它

    Route::get('/', [
        'as' => 'products.index', 
        'uses' => 'CustomerProductController@index'
    ])->middleware('throttleIp:60,1');
    

    【讨论】:

    • 它确实有帮助。非常感谢。
    猜你喜欢
    • 2020-09-02
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2017-05-16
    相关资源
    最近更新 更多