Php – Preventing Brute-Force Attacks When Authenticating A User in Laravel

brute-forcelaravelPHP

Is it possible to use Laravel's Authenticating A User With Conditions to prevent brute-force attacks?

This answer for PHP, suggests adding two columns to your database (TimeOfLastFailedLogin and NumberOfFailedAttempts) and then checking against those values on each login attempt.

Here is the Laravel syntax to authenticate a user with conditions:

if (Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1)))
{
    // The user is active, not suspended, and exists.
}

Is there any way to use the condition parameters to check number of attempts against a specified period of time? E.g., less than 3 requests in the last 60 seconds.

Best Answer

You can create something as simple as the class below to help you prevent that:

class Login {

    public function attempt($credentials)
    {
        if ( ! $user = User::where('email' => $credentials['email'])->first())
        {
            //throw new Exception user not found
        }

        $user->login_attempts++;

        if ($user->login_attempts > 2)
        {
            if (Carbon::now()->diffInSeconds($user->last_login_attempt) < 60)
            {
                //trow new Exception to wait a while
            }

            $user->login_attempts = 0;
        }

        if ( ! Auth::attempt($credentials))
        {
            $user->last_login_attempt = Carbon::now();

            $user->save();

            //trow new Exception wrong password
        }

        $user->login_attempts = 0;

        $user->save();

        return true;
    }

}

Or you can go with a package, like Sentry, which controls throttling for you. Sentry is open source.

Related Topic