Laravel Throttle中间件:它有回调/处理程序吗?

时间:2016-12-15 10:55:34

标签: laravel laravel-5 throttling

我想使用Laravel's Throttle Middleware,但我还要记录用户尝试过多的任何情况。

是否有任何回调/处理程序,我可以检测到它并对其执行某些操作?

假设我有这样的路线:

Route::get('foo', array('before' => 'throttle:5,10', function () {
    return 'You shall pass!';
}, ));

3 个答案:

答案 0 :(得分:3)

如果达到最大计数,则会触发此事件:

Illuminate\Auth\Events\Lockout

所以你可以听听它

protected $listen = [
    ...
    'Illuminate\Auth\Events\Lockout' => [
        'App\Listeners\LogLockout',
    ],
];

答案 1 :(得分:0)

您可以扩展ThrottleRequests类并重新声明其buildException,或尝试在\Symfony\Component\HttpKernel\Exception\HttpException内处理其异常(app/Exceptions/Handler.php,429'尝试次数太多。')。

答案 2 :(得分:0)

Illuminate\Auth\Events\Lockout事件仅在Illuminate\Foundation\Auth\ThrottlesLogins中触发,但您仍然可以手动触发它。

这是我做到的方式:

  1. app/Exceptions/Handler.php中添加以下use语句:
use Illuminate\Auth\Events\Lockout;
use Symfony\Component\HttpKernel\Exception\HttpException;
  1. 将其添加到同一文件的report方法中:
if ($exception instanceof HttpException) {
    if ('Too Many Attempts.' == $exception->getMessage()) {
        event(new Lockout(request()));
    }
}
  1. 执行php artisan make:listener LogThrottleLimitReached并将此代码添加到handle文件的app/Listeners/LogThrottleLimitReached.php方法内:
$request = $event->request;

\Log::error(sprintf(
    'Throttling rate limit reached. URL: %s, Body: %s, IP: %s',
    $request->url(),
    json_encode($request->all()),
    $request->ip()
));
  1. app/Providers/EventServiceProvider.php中注册该监听器:
use App\Listeners\LogThrottleLimitReached;
use Illuminate\Auth\Events\Lockout;

protected $listen = [
    Lockout::class => [
        LogThrottleLimitReached::class,
    ],
];