简体   繁体   English

在 Laravel 中禁用速率限制器?

[英]Disable rate limiter in Laravel?

Is there a way to disable rate limiting on every/individual routes in Laravel?有没有办法禁用 Laravel 中每个/单个路由的速率限制?

I'm trying to test an endpoint that receives a lot of requests, but randomly Laravel will start responding with { status: 429, responseText: 'Too Many Attempts.' }我正在尝试测试接收大量请求的端点,但随机 Laravel 将以{ status: 429, responseText: 'Too Many Attempts.' }开始响应。 { status: 429, responseText: 'Too Many Attempts.' } for a few hundred requests which makes testing a huge pain. { status: 429, responseText: 'Too Many Attempts.' }对于几百个请求,这使得测试变得非常痛苦。

In app/Http/Kernel.php Laravel has a default throttle limit for all api routes.app/Http/Kernel.php Laravel 对所有 api 路由都有一个默认的节流限制。

protected $middlewareGroups = [
    ...
    'api' => [
        'throttle:60,1',
    ],
];

Comment or increase it.评论或增加它。

You can actually disable only a certain middleware in tests.您实际上只能在测试中禁用某个中间件。

use Illuminate\Routing\Middleware\ThrottleRequests;

class YourTest extends TestCase 
{

    protected function setUp()
    {
        parent::setUp();
        $this->withoutMiddleware(
            ThrottleRequests::class
        );
    }
    ...
}

Assuming you are using the API routes then you can change the throttle in app/Http/Kernel.php or take it off entirely.假设您正在使用 API 路由,那么您可以更改 app/Http/Kernel.php 中的节流阀或完全取消它。 If you need to throttle for the other routes you can register the middleware for them separately.如果您需要对其他路由进行节流,您可以分别为它们注册中间件。

(example below: throttle - 60 attempts then locked out for 1 minute) (以下示例:油门 - 60 次尝试,然后锁定 1 分钟)

'api' => [
        'throttle:60,1',
        'bindings',
    ],

您可以使用cache:clear命令清除包括速率限制在内的缓存,如下所示:

php artisan cache:clear

In Laravel 5.7在 Laravel 5.7 中

Dynamic Rate Limiting You may specify a dynamic request maximum based on an attribute of the authenticated User model.动态速率限制您可以根据经过身份验证的用户模型的属性指定动态请求最大值。 For example, if your User model contains a rate_limit attribute, you may pass the name of the attribute to the throttle middleware so that it is used to calculate the maximum request count:例如,如果您的 User 模型包含 rate_limit 属性,您可以将该属性的名称传递给油门中间件,以便使用它来计算最大请求数:

Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {
    Route::get('/user', function () {
        //
    });
});

https://laravel.com/docs/5.7/routing#rate-limiting https://laravel.com/docs/5.7/routing#rate-limiting

If you want to disable just for automated tests, you can use the WithoutMiddleware trait on your tests.如果您只想为自动化测试禁用,您可以在测试中使用WithoutMiddleware特性。

use Illuminate\Foundation\Testing\WithoutMiddleware;

class YourTest extends TestCase {
    use WithoutMiddleware;

    ...

Otherwise, just remove the 'throttle:60,1', line from your Kernel file ( app/Http/Kernel.php ), and your problem will be solved.否则,只需从您的内核文件 ( app/Http/Kernel.php ) 中删除'throttle:60,1',行,您的问题就会得到解决。

A non-hacky way to increase the throttle in unit tests to avoid the dreaded 429:在单元测试中增加油门以避免可怕的 429 的非黑客方法:

  1. Remove the throttle:60,1 from the kernel file middleware.从内核文件中间件中删除油门:60,1。
  2. Add the throttle middleware back in to the route group, using an environment variable instead:使用环境变量将油门中间件重新添加到路由组中:
$requestsPerMinute = ENV("REQUESTS_PER_MINUTE", 60);
Route::middleware(["auth:api", "throttle:$requestsPerMinute,1"])->group(function(){
  // your routes
});
  1. Define the REQUESTS_PER_MINUTE environment variable much higher in phpunit.xml, to allow more requests in test environment before throttling.在 phpunit.xml 中定义更高的 REQUESTS_PER_MINUTE 环境变量,以在限制之前在测试环境中允许更多请求。
<server name="REQUESTS_PER_MINUTE" value="500"/>
  1. (Also define the new REQUESTS_PER_MINUTE var in .env, even though it'll fall back to 60). (还要在 .env 中定义新的 REQUESTS_PER_MINUTE 变量,即使它会回退到 60)。

You can add the following lines in your app/Http/Kernel.php您可以在app/Http/Kernel.php添加以下几行

    'api' => [
        'throttle:120,1',
        'bindings',
         \App\Library\Cobalt\Http\Middleware\LogMiddleware::class,
    ],

If the problem persists try the artisan command php artisan cache:clear如果问题仍然存在,请尝试使用 artisan 命令php artisan cache:clear

If you are using Laravel 8.x or later you can use RateLimiter with the following steps:如果您使用的是 Laravel 8.x 或更高版本,您可以通过以下步骤使用 RateLimiter:

In your app/Providers/RouteServiceProvider.php find below configureRateLimiting: protected function configureRateLimiting() {在你的 app/Providers/RouteServiceProvider.php 中找到下面的 configureRateLimiting: protected function configureRateLimiting() {

    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
    });

    // no limit throttle
    RateLimiter::for('none', function (Request $request) {
        return Limit::none();
    });

}

In your app/web.php add 'throttle:none:在你的 app/web.php 添加 'throttle:none:

Route::group(['middleware' => ['auth', 'throttle:none']], function ($router) {
    Route::post('test', 'TestController@test');
});

In my case, I just changed the default value of perMinute() in `App\\Providers\\RouteServiceProvider.就我而言,我只是更改了 App\\Providers\\RouteServiceProvider 中perMinute()的默认值。

protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            $perMinute = env('APP_ENV') === 'testing' ? 1000 : 60;

            return Limit::perMinute($perMinute)
              ->by(optional($request->user())->id ?: $request->ip());
        });
    }

You can remove or comment out the line (throttle:60,1) from App\Http\Kernel.php.您可以从 App\Http\Kernel.php 中删除或注释掉行(throttle:60,1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM