繁体   English   中英

Laravel:在自定义登录中集成 Throttle

[英]Laravel: Integrating Throttle in Custom Login

如果我没有使用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');

    }
  }

我想限制失败的登录,但我似乎无法使用我自己的控制器使其工作。 你们能帮帮我吗?

在您的方法中添加以下代码。 把它放在第一位

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

现在在登录失败的地方添加以下代码。 这将增加失败的尝试次数。

$this->incrementLoginAttempts($request);

成功登录后,添加以下代码以使其重置。

$this->clearLoginAttempts($request);

尝试向控制器的构造函数添加节流,如下所示:

/**
 * Create a new login controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('throttle:3,1')->only('login');
}

不幸的是,Laravel 文档并没有多说节流: https ://laravel.com/docs/6.x/authentication#login-throttling

但是,字符串的3,1部分对应最多 3 次尝试,衰减时间为 1 分钟。

throttle可以在routeMiddleware数组的/project-root/laravel/app/Http/Kernel.php中定义,如下所示:
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, . Laravel 文档在此处解释了此方法: https ://laravel.com/docs/6.x/middleware#assigning-middleware-to-routes

使用 Illuminate\Foundation\Auth 中存在的 Trait ThrottlesLogins 并覆盖下面提到的 2 个函数。 我已经在 Laravel 5.6 上测试过它并且工作正常。

public function maxAttempts()
{
    //Lock out on 5th Login Attempt
    return 5;
}

public function decayMinutes()
{
    //Lock for 1 minute
    return 1;
}
Route::post('login', ['before' => 'throttle:2,60', 'uses' => 'YourLoginController@Login']);

虽然,这个答案已经很晚了,但这是我所做的,并且奏效了。 我希望它也能帮助你。 我正在使用 laravel 5.2。

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\MessageBag;
use Cookie;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class UserController extends Controller
{
/** Add This line on top */
use AuthenticatesAndRegistersUsers,ThrottlesLogins;
/** This way, you can control the throttling */
protected $maxLoginAttempts=3;
protected $lockoutTime=300;

public function postUserSignIn(Request $request)
{
    /** This line should be in the start of method */
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);
        return $this->sendLockoutResponse($request);
    }
    /** Validate the input */
    $validation = $this->validate($request,[
        'email' => 'required|email',
        'password' => 'required|min:4'
    ]);

    /** Validation is done, now login user */
    //else to user profile
    $check = Auth::attempt(['email' => $request['email'],'password' => $request['password']]);

    if($check){

        $user = Auth::user();
        /** Since Authentication is done, Use it here */
        $this->clearLoginAttempts($request);
        if ($user->role == 1 || $user->role == 2){
            if(Session::has('cart')){
                return redirect()->route('cart');
            }
            return redirect()->intended();
        }elseif($user->role == 99) {
            return redirect()->route('dashboard');
        }

    }else{
        /** Authentication Failed */
        $this->incrementLoginAttempts($request);
        $errors = new MessageBag(['password' => ['Email and/or Password is invalid']]);
        return redirect()->back()->withErrors($errors);
    }

}

}

if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return redirect()->route('login')->with('alert-warning', 'Too many login attempts');
        }

protected function hasTooManyLoginAttempts(Request $request)
{
   $maxLoginAttempts = 3;

   $lockoutTime = 1; // In minutes

   return $this->limiter()->tooManyAttempts(
       $this->throttleKey($request), $maxLoginAttempts, $lockoutTime
   );
}

试试我的版本:

use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller{
use AuthenticatesUsers;
public function login(Request $request){
    if($this->hasTooManyLoginAttempts($request)){
        $this->fireLockoutEvent($request);
        return $this->sendLockoutResponse($request);
    }else{
        if (Auth::attempt(['username' => $request->login_username, 'password' => $request->login_password])) {
        session()->put(['username'=>Auth::user()->username,'userid'=>Auth::user()->id]);
        return redirect()->intended('anydashboard');
        }else{
            $this->incrementLoginAttempts($request);
            //my '/' path is the login page, with customized response msg...
            return redirect('/')->with(['illegal'=>'Login failed, please try again!'])->withInput($request->except('password'));
        }
    }
}
}

为了使用 Eloquent Model Auth(默认),你的 AUTH_MODEL 应该实现 AuthenticatableContract,所以仔细检查你的模型:

namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
//protected $fillable = [];
...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM