是否可以使用Laravel的Authenticating A User With Conditions来防止暴力攻击?
对于PHP,这个答案建议在数据库中添加两列(TimeOfLastFailedLogin
和NumberOfFailedAttempts
),然后在每次登录时检查这些值。
以下是Laravel语法,用于根据条件对用户进行身份验证:
if (Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1)))
{
// The user is active, not suspended, and exists.
}
是否有任何方法可以使用条件参数来检查指定时间段内的尝试次数?例如,在过去60秒内少于3个请求。
您可以创建像下面这样简单的类来帮助您防止这种情况:
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是开源的。
我知道这是一个老问题,但由于它在谷歌上排名很高,我想澄清的是,ThrottlesLogins的特性自Laravel 5.1以来就一直存在,并且确实可以防止暴力攻击。
默认情况下,它通过特征AuthenticatesUser包含在Auth''LoginController中。
文档:https://laravel.com/docs/5.6/authentication#login-节流
默认行为示例(请参见方法"登录"):https://github.com/laravel/framework/blob/5.6/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
因此,如果您使用Laravel附带的默认登录控制器,那么登录限制的处理将自动完成。