You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义Laravel登录控制器的用户一小时锁定时长?

解决Laravel登录失败后锁定1小时的问题

你当前的代码中,RateLimiter::hit()方法默认使用60秒的冷却时长,要实现1小时锁定,只需给hit()方法传入第三个参数(锁定时长,单位为秒,1小时=3600秒)即可。

修改后的完整代码如下:

public function login(Request $request)
{
    // 定义锁定时长:1小时 = 3600秒
    $lockoutSeconds = 3600;
    $key = optional($request->user())->id ?: $request->ip();

    if (RateLimiter::tooManyAttempts($key, 5, $lockoutSeconds)) {
        return response()->json([
            'message' => 'Account locked for an hour'
        ]);
    }

    $credentials = request(['email', 'password']);

    if (! Auth::attempt($credentials)) {
        // 传入第三个参数指定锁定时长
        RateLimiter::hit($key, $lockoutSeconds);

        return response()->json([
            'status_code' => 401,
            'message' => 'Unauthorized',
        ]);
    } else {
        RateLimiter::clear($key);

        return response()->json([
            'status_code' => 200,
            'message' => 'Welcome',
        ]);
    }
}

修改说明:

  1. 新增$lockoutSeconds变量统一管理锁定时长,方便后续调整;
  2. 在RateLimiter::tooManyAttempts()中添加第三个参数$lockoutSeconds,确保检查的时长和锁定时长一致;
  3. 在RateLimiter::hit()中传入第三个参数$lockoutSeconds,设置每次失败尝试后的锁定时长为1小时。

这样修改后,当用户连续5次登录失败,就会被锁定1小时,直到缓存中的限制记录过期。

内容的提问来源于stack exchange,提问作者BigJobbies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:25:21