Jan*_*Tho 7 php validation throttling laravel laravel-5.4
如果我没有使用laravel给出的默认LoginController,如何集成laravel throttle?
这是我的控制器:
use AuthenticatesUsers;
//function for login
public function login(Request $requests){
$username = $requests->username;
$password = $requests->password;
/**to login using email or username**/
if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
Auth::attempt(['email' => $username, 'password' => $password]);
} else {
Auth::attempt(['username' => $username, 'password' => $password]);
}
if(Auth::check()){
if(Auth::user()->type_user == 0){
return view('users.dashboard');
}
else{
return view('admin.dashboard');
}
}
else{
return Redirect::back()->withInput()->withErrors(['message'=>$login_error],'login');
}
}
Run Code Online (Sandbox Code Playgroud)
我想限制失败的登录,但我似乎无法使用我自己的控制器.你能帮帮我吗?
在您的方法中添加以下代码。让它成为第一件事
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
Run Code Online (Sandbox Code Playgroud)
现在在登录失败的地方添加以下代码。这将增加失败的尝试计数。
$this->incrementLoginAttempts($request);
Run Code Online (Sandbox Code Playgroud)
成功登录后,添加以下代码使其重置。
$this->clearLoginAttempts($request);
Run Code Online (Sandbox Code Playgroud)
尝试将节流添加到控制器的构造函数中,如下所示:
/**
* Create a new login controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('throttle:3,1')->only('login');
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,Laravel 文档并没有对节流说太多:https ://laravel.com/docs/6.x/authentication#login-throttling
但是,3,1字符串的部分对应于最多 3 次尝试,衰减时间为 1 分钟。
throttle可被定义在/project-root/laravel/app/Http/Kernel.php所述的routeMiddleware阵列,如下所示:
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,。Laravel 文档在这里解释了这种方法:https ://laravel.com/docs/6.x/middleware#assigning-middleware-to-routes
小智 1
Route::post('login', ['before' => 'throttle:2,60', 'uses' => 'YourLoginController@Login']);
Run Code Online (Sandbox Code Playgroud)