Laravel Passport oauth/token 访问频率控制

最近在项目碰到了一个问题,在高并发访问情况下 出现了token 获取不到 报错如下

 "message": "Client error: `POST http://127.0.0.1:8081/oauth/token` resulted in a `429 Too Many Requests` response:\n<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <meta charset=\"utf-8\">\n        <meta http-equiv=\"X-UA-Compatible\" co (truncated...)\n",
    "exception": "GuzzleHttp\\Exception\\ClientException",
    "file": "/home/www/shifeng/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php",
    "line": 113,
    "trace": [
        {
            "file": "/home/www/shifeng/vendor/guzzlehttp/guzzle/src
			

解决思路

  • 通过压力测试发现,一分钟内只能发起30次请求。
  • throttle 中间件我们已经熟知,也检查了Kernel.php 中的 api 的 throttle 配置,已经配置成10000,1 应该不会存在这样的问题。
  • 既然不是系统的throttle中间件引起的,那就想到了passport拓展中是不是可能做了限制,故查看passport模块中的路由配置文件RouteRegistrar.php,发现如下:

    /**
     * Register the routes for retrieving and issuing access tokens.
     *
     * @return void
     */
    public function forAccessTokens()
    {
        $this->router->post('/token', [
            'uses' => 'AccessTokenController@issueToken',
            'middleware' => 'throttle',
        ]);

        $this->router->group(['middleware' => ['web', 'auth']], function ($router) {
            $router->get('/tokens', [
                'uses' => 'AuthorizedAccessTokenController@forUser',
            ]);

            $router->delete('/tokens/{token_id}', [
                'uses' => 'AuthorizedAccessTokenController@destroy',
            ]);
        });
    }
  • 发现这里获取token的接口中 也存在throttle中间件,而这里默认的配置是 30,1 也就是一分钟内限制30次请求访问。
  • 通过修改参数值解决,将throttle修改成throttle:10000,1 基本解决大量访问请求,当然也可以直接取消这里的throttle中间件配置,直接去掉 'middleware' => 'throttle', 这行代码即可。