使用JWT Auth时,Laravel 5.3节流登录

时间:2017-01-14 19:35:44

标签: laravel laravel-5 jwt laravel-5.3 laravel-authorization

我在我的Laravel + Angular应用程序中使用JWT。我看到Laravel 5.3具有开箱即用的登录限制功能。但是,在使用JWT Auth时如何才能使其工作?我有以下代码,但登录限制不起作用。尽管尝试失败了多次,但我只收到Invalid Login Details错误,但它没有限制并显示Too many logins错误:

class LoginController extends Controller
{
     use AuthenticatesUsers;

     protected $maxLoginAttempts=5;
     protected $lockoutTime=300;

    public function login(Request $request)
    {
      $credentials = $request->only('email', 'password');

      $this->validate($request, [
        'email' => 'required',
        'password' => 'required',
      ]);

      if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return response()->json(['error' => 'Too many logins'], 400);
      }

      try {
        if (! $token = JWTAuth::attempt($credentials)) {
          return response()->json(['error' => 'Invalid Login Details'], 401);
        }
      } catch (JWTException $e) {
        // something went wrong
        $this->incrementLoginAttempts($request);
        return response()->json(['error' => 'Could Not Create Token'], 500);
      }

      // if no errors are encountered we can return a JWT
      return response()->json(compact('token'));
    }
}

如何使用JWTAuth使用此功能?你能帮我一个人吗?

1 个答案:

答案 0 :(得分:4)

这是因为你是JWTAuth没有抛出异常来增加你的登录尝试。只需将$this->incrementLoginAttempts($request);置于auth失败状态,如下所示:

if (! $token = JWTAuth::attempt($credentials)) {
$this->incrementLoginAttempts($request);
return response()->json(['error' => 'Invalid Login Details'], 401);
}