【问题标题】:Laravel display warning before rate limit lockoutLaravel 在速率限制锁定之前显示警告
【发布时间】:2022-09-24 01:37:43
【问题描述】:

我的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 次后锁定用户。

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

这可能吗?我找不到有关此的任何信息。

干杯,

    标签: laravel laravel-8


    【解决方案1】:

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

    手动与RateLimiter 类和manually increment the limiter 交互会容易得多,这样,您可以返回剩余的尝试和所有其他信息。

    这是一个基本的例子;

    添加课程use Illuminate\Support\Facades\RateLimiter;

    然后手动调用hit 并计算剩余的尝试次数,

    Route::get('/whatever-login-route', function( Request $request ) {
        
        $key = 'login-limit:'.$request->ip;
    
        //RateLimiter::resetAttempts( $key ); // resetting attempts
    
        return [
            'hit' => RateLimiter::hit($key, 3600),
            'remaining' => RateLimiter::remaining($key, 5),
            'reset_at' => RateLimiter::availableIn($key)
        ];
    
    });
    

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

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 2017-08-20
      • 2022-08-08
      • 2017-05-07
      • 2016-02-18
      • 2016-03-01
      • 2021-04-05
      • 1970-01-01
      相关资源
      最近更新 更多