Laravel add login throttling with custom login controller

David Carr

2 min read - 3rd Jan, 2018

When using a custom login controller by default it won't have the login throttling applied.

Login throttling will stop a user attempting to login repeatedly after a set number of login attempts has been made. When locked out no login's will be allowed until a set amount of time has passed.

To add this create a hasTooManyLoginAttempts method to your controller, inside the method set the number of login attempts allowed and the number of minutes a lockout will last for, in this example, 5 attempts are allowed if exceeded a lockout will happen for 10 minutes.

/**
 * Determine if the user has too many failed login attempts.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function hasTooManyLoginAttempts(Request $request)
{
    $attempts = 5;
    $lockoutMinites = 10;
    return $this->limiter()->tooManyAttempts(
        $this->throttleKey($request), $attempts, $lockoutMinites
    );
}

This method will get used as long as your login method called it like this:

public function login(Request $request)
{
    $this->validateLogin($request);

    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

        return $this->sendLockoutResponse($request);
    }

    if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);
    }

    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    $this->incrementLoginAttempts($request);

    return $this->sendFailedLoginResponse($request);
}

 

0 comments
Add a comment

Copyright © 2006 - 2024 DC Blog - All rights reserved.