速率限制锁定前,Laravel显示警告



我的RouteServiceProvider.php中有一个自定义的速率限制规则,看起来是这样的;

protected function configureRateLimiting()
{
RateLimiter::for('example', function (Request $request) {
return Limit::perHour(5)->by(optional($request->user())->id ?: $request->ip())->response(function () {
return response()->view('auth.login', [
'error' =>
'You have exceeded the maximum number of login attempts. ' .
'Your account has been blocked for security reasons.',
'page' => 'login',
], 422);
});
});
}

这会在一小时内尝试5次后锁定用户。

我想在两次尝试后添加一个警告,类似于you have had two failed login attempts. If you continue entering an incorrect password your account will be locked.

我在我的登录控制器中尝试了以下操作,但不起作用;

if (RateLimiter::remaining(optional($request->user())->id ?: $request->ip(), 2)) {
RateLimiter::hit(optional($request->user())->id ?: $request->ip());
return view('auth.login')->with([
'error' => 'You have had two failed login attempts. If you continue entering an incorrect password your account will be locked.',
'page' => 'login'
]);
}

这可能吗?我找不到这方面的任何信息。

干杯,

速率限制器信息将被传递到响应标头X-RateLimit-LimitX-RateLimit-Remaining中,您可能无法提取

手动与RateLimiter类交互并手动增加限制器会容易得多,这样,您可以返回剩余的尝试和所有其他信息。

这里有一个基本的例子;

添加类别use IlluminateSupportFacadesRateLimiter;

然后手动调用CCD_ 7并计数剩余的尝试,

Route::get('/whatever-login-route', function( Request $request ) {

$key = 'login-limit:'.$request->ip;
//RateLimiter::resetAttempts( $key ); // resetting attempts
//RateLimiter::clear( $key ); // resetting attempts and lockout timer
return [
'hit' => RateLimiter::hit($key, 3600),
'remaining' => RateLimiter::remaining($key, 5),
'reset_at' => RateLimiter::availableIn($key)
];
});

这只是一个基本示例,但正如您所看到的,在您的登录控制器中,您可以传递remaininghit值,并在2次点击后发出警告消息,如果remaining值小于1或hit值大于5,则返回带有429标头的错误消息。

案例中的示例用法

$key = optional($request->user())->id ?: $request->ip(); 
$hit = RateLimiter::hit($key, 3600 ); // 2nd parameter is the value lockout timer in seconds
$remaining = RateLimiter::remaining($key, 5) // 2nd parameter is the number of allowed attempts in lockout define above
if ( $hit == 2 ) { // if ( $remaining == 3 )
return view('auth.login')->with([
'error' => 'You have had two failed login attempts. If you continue entering an incorrect password your account will be locked.',
'page' => 'login'
]);
}

最新更新