Search code examples
laravellaravel-5jwtlaravel-5.3laravel-authorization

Laravel 5.3 Throttle Login When Using JWT Auth


I am using JWT for my Laravel + Angular application. I see Laravel 5.3 has login throttling feature out of the box. But how can I get this to work when using JWT Auth? I have the following code but the login throttling is not working. Inspite of numerous failed attempts, I only get the Invalid Login Details error but its not throttling and showing Too many logins error:

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

How do you use this feature using using JWTAuth? Can you someone help me out please?


Solution

  • This is because you're JWTAuth is not throwing exception to increment your login attempt. Simply put $this->incrementLoginAttempts($request); inside condition for auth failing like so:

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