2014-09-24 61 views
5

是否可以使用Laravel的Authenticating A User With Conditions来防止暴力攻击?在Laravel验证用户时防止暴力攻击

这个answer for PHP,建议在您的数据库中添加两列(TimeOfLastFailedLoginNumberOfFailedAttempts),然后在每次登录尝试时检查这些值。

这里是Laravel的语法与条件验证用户的身份:

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

有没有办法使用条件参数来检查尝试的次数对指定的时间段?例如,在最近60秒内少于3次的请求。

回答

9

您可以创建简单,下面的类来帮助你的东西防止:

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; 
    } 

} 

或者你可以用一个包去,像Sentry,控制节流你。 Sentry是开源的。

1

我知道这是一个古老的问题,但是因为它在Google上排名很好,我想澄清一下,自从Laravel 5.1起,ThrottlesLogins特性一直存在,并且确实可以防止暴力攻击。

它默认包含在Auth \ LoginController中。