首页 > 解决方案 > 在 laravel 中处理 hasTooManyLoginAttempts?

问题描述

用户已经超过了他们分配的最大登录尝试次数,这将通过用户名和客户端的 IP 地址进行键入,我使用 trait AuthenticatesUsers 拉入。您查看提到的特征内部,您会看到另一个特征 ThrottlesLogins 拉入。

授权配置:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
        'admin-web' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'admin-api' => [
            'driver' => 'passport',
            'provider' => 'admins',
        ],
    ],

授权控制器:

 class AuthController extends Controller
    {

     use ThrottlesLogins;

  public function login(Request $request)
        {
            $method = __FUNCTION__;

            //set validations
            $validator = Validator::make($request->all(), [
                'email' => 'required|string|email',
                'password' => 'required|string|min:6',
            ]);
            if ($validator->fails()) {
                return (new FailedServerResponse($this->controller, $method, $this->errorType['validation'], $validator->errors()))->show();
            }

            $admin = Admin::where('email', $request->email)->first();

            if ( $this->hasTooManyLoginAttempts($request)) {
               $this->fireLockoutEvent($request);
               return $this->sendLockoutResponse($request);
            }

            if (Auth::guard('admin-web')->attempt(['email' => $request->email, 'password' => $request->password, 'is_active' => 1], true)) {
                try {
                    $token = $admin->createToken('register admin')->accessToken;
                } catch (\Exception $e) {
                    return (new FailedServerResponse($this->controller, $method, $this->errorType['token']))->show();
                }

                return $token;
                //success and everything is ok
                $extra = ['token' => $token, 'is_register' => true];
                return (new UserResponse($admin->load('userActivities', 'addresses.city.province', 'wallets', 'userGalleries'), $actionName, $extra))->withPrimaryLayout();

            } else {
                return (new FailedServerResponse($this->controller, $method, $this->errorType['notFound']))->show();
            }
        }

     protected function hasTooManyLoginAttempts(Request $request)
        {
            $attempts = 2;
            $lockoutMinites = 10;
            return $this->limiter()->tooManyAttempts(
                $this->throttleKey($request), $attempts, $lockoutMinites
            );
        }

hasTooManyLoginAttempts 不起作用。你能帮助我吗?

标签: phplaravel

解决方案


也许问题在于

$this->incrementLoginAttempts($request);

如果登录尝试不成功,我们将增加尝试登录的次数并将用户重定向回登录表单。


推荐阅读