我想使用Laravel's Throttle Middleware,但我还要记录用户尝试过多的任何情况。
是否有任何回调/处理程序,我可以检测到它并对其执行某些操作?
假设我有这样的路线:
Route::get('foo', array('before' => 'throttle:5,10', function () {
return 'You shall pass!';
}, ));
答案 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
中触发,但您仍然可以手动触发它。
这是我做到的方式:
app/Exceptions/Handler.php
中添加以下use
语句:use Illuminate\Auth\Events\Lockout;
use Symfony\Component\HttpKernel\Exception\HttpException;
report
方法中:if ($exception instanceof HttpException) {
if ('Too Many Attempts.' == $exception->getMessage()) {
event(new Lockout(request()));
}
}
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()
));
app/Providers/EventServiceProvider.php
中注册该监听器:use App\Listeners\LogThrottleLimitReached;
use Illuminate\Auth\Events\Lockout;
和
protected $listen = [
Lockout::class => [
LogThrottleLimitReached::class,
],
];