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

Laravel手动认证:RateLimiter::tooManyAttempts始终返回false

Laravel 10手动认证RateLimiter不生效的解决办法

你代码里的核心问题是:只做了登录次数超限检查,但从未在登录失败时累加失败次数,RateLimiter的计数器根本没被触发,所以tooManyAttempts永远返回false。

按下面的步骤修改代码即可解决:

  1. 登录失败时记录尝试次数:在认证失败的分支里调用RateLimiter::hit()方法,累加失败计数
  2. 登录成功时清除失败记录:认证通过后调用RateLimiter::clear()重置计数器,避免后续被错误限制
  3. 修正超限检查的逻辑判断(你原来的判断条件写反了)

修改后的完整代码:

use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use App\Providers\RouteServiceProvider;

public function login(LoginRequest $loginRequest)
{
    // 先检查是否超限,超限直接拦截
    $this->checkTooManyFailedAttempts();

    $email = $loginRequest->email;
    $password = $loginRequest->password;
    $remember = (bool)$loginRequest->remember;

    if (Auth::attempt(['email' => $email, 'password' => $password, 'is_verified' => 1], $remember)) {
        // 登录成功,清除该用户+IP的失败记录
        RateLimiter::clear($this->throttleKey());
        return redirect()->intended(RouteServiceProvider::HOME);
    } else {
        // 登录失败,累加尝试次数
        RateLimiter::hit($this->throttleKey());
        return redirect()->route('auth.login.show')->with('error', 'The email and password you entered did not match our records. Please double-check and try again.');
    }
}

public function throttleKey()
{
    return Str::lower(request('email')) . '|' . request()->ip();
}

public function checkTooManyFailedAttempts()
{
    if (RateLimiter::tooManyAttempts($this->throttleKey(), 3)) {
        throw new Exception('IP address banned. Too many login attempts.');
    }
}

额外补充细节:

  • 若需要自定义封禁时长,可在hit()方法中传入第二个参数,比如RateLimiter::hit($this->throttleKey(), 300)表示封禁5分钟
  • 可以用RateLimiter::availableIn($this->throttleKey())获取剩余封禁秒数,方便在错误提示里告知用户解封时间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:42:15