Laravel 5: Security – maxLoginAttempts and lockoutTime
Lets bring back maxLoginAttempts and lockoutTime phased out by ThrottlesLogins trait.
Here is one of approaches – you just need to tweak trait ThrottlesLogins and you are good to go.
When you use Laravel built in authentication scaffolding, setup, brought you by this command:
1 2 3 |
php artisan make:auth |
… inside of your LoginController, you will see trait AuthenticatesUsers pulled in.
When you look inside of mentioned trait, you will see another trait ThrottlesLogins pulled in.
This is the one we need to tweak.
step 1
Find our ThrottlesLogins trait:
1 2 3 |
vendor\laravel\framework\src\Illuminate\Foundation\Auth\ThrottlesLogins.php |
… and change protected function hasTooManyLoginAttempts to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** * Determine if the user has too many failed login attempts. * * @param \Illuminate\Http\Request $request * @return bool */ protected function hasTooManyLoginAttempts(Request $request) { return $this->limiter()->tooManyAttempts( $this->throttleKey($request), $this->setLoginAttempts(), $this->setLockoutTime() //this line has changed ); } |
Above our changed protected function hasTooManyLoginAttempts, add two extra methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/** * Amount of bad attempts user can make, before being locked out * default: 5 attempts * jp[20170203] * * @return integer */ protected function setLoginAttempts() { if (method_exists($this, 'maxLoginAttempts')) { return $this->maxLoginAttempts(); } return property_exists($this, 'maxLoginAttempts') ? $this->maxLoginAttempts : 5; } /** * Time for which user is going to be blocked in minutes(!) * default: 1 minute * jp[20170203] * * @return integer */ protected function setLockoutTime() { if (method_exists($this, 'lockoutTime')) { return $this->lockoutTime(); } return property_exists($this, 'lockoutTime') ? $this->lockoutTime : 1; } |
Now you can set how many attempt and how long cool-down period you need (in minutes) directly in LoginController pulling in trait AuthenticatesUsers or anywhere, where you directly pull trait ThrottlesLogins.
login attempts:
1 2 3 4 5 6 7 8 9 10 |
//use protected property protected $maxLoginAttempts = 3; // number of bad attempts user can make //OR use protected method protected function maxLoginAttempts() { return 1; //int this sample one bad trial allowed } |
login cool-down:
1 2 3 4 5 6 7 8 9 10 |
//use protected property protected $lockoutTime = 2; // period for which user is going to be blocked in minutes //OR use protected method protected function lockoutTime() { return 3; //in this sample: 3 minutes cool-down } |
Tested and works in Laravel 5.3 and Laravel 5.4.
Laravel 5.2 offers maxLoginAttempts and lockoutTime out of the box.
I have no idea how it plays with Laravel 5.1 or 5.0, as I have not tested it.
That’s about the size of it.