5

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.

Community
  • 1
  • 1
Justin
  • 22,998
  • 16
  • 104
  • 122

2 Answers2

10

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.

Antonio Carlos Ribeiro
  • 79,934
  • 19
  • 200
  • 195
3

I know this is an old question, but as it ranks well on Google I would like to clarify that the trait ThrottlesLogins has been around since Laravel 5.1, and does prevent from brute force attacks.

It is included in Auth\LoginController per default through the trait AuthenticatesUser.

Docs: https://laravel.com/docs/5.6/authentication#login-throttling

Example of default behaviour (see method "login"): https://github.com/laravel/framework/blob/5.6/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php

So if you are using the default loginController that comes with Laravel, then the handling of login throtteling will be done automatically.

thephper
  • 1,235
  • 12
  • 17
  • If you add a link to docs and a snippet of how to implement I'll mark it as the correct answer. – Justin Mar 12 '18 at 22:48
  • I have tried explaining a bit more, but as it is default behaviour now, I don't think an implementation example would be necessary. – thephper Mar 13 '18 at 18:37