Laravel provides an easy way to work around the rate-limiting, for example, I want to restrict the failed login attempt by IP if the user fails to log in 3 times in a row in a minute. In this case, we can use the RateLimiter facade provided by Laravel which is really easy to understand and work around.
Function
RateLimiter::tooManyAttempts() accepts two parameters the first parameter is the key use to identify the attempt, in this case, we use IP address as we want to restrict it by IP address only, the second parameter is how many attempts till you want to restrict.
RateLimiter::hit() this function will increment the attempt by key. The first parameter is the key you want to increment the attempt, second parameter number of seconds that the attempt will expire.
RateLimiter::clear() this function accepts the key as a parameter where you want to clear the attempt. You can see that we clear the login attempt when the user login success as we don’t care about the login attempt when the login success.
Code
use Illuminate\Support\Facades\RateLimiter;
public function login(Request $request)
{
try {
if (RateLimiter::tooManyAttempts(request()->ip(), 3)) {
return response()->json(
[ 'message' => 'Too many fail login attempt your ip has restricted for 1 minute.' ],
Response::HTTP_UNAUTHORIZED
);
}
$user = User::where('email', $request->email)->first();
$check = null;
if ($user) {
$check = Hash::check($request->password, $user->password);
}
if (!$check) {
RateLimiter::hit(request()->ip(), 60);
return response()->json([ 'message' => 'Invalid credential' ], Response::HTTP_UNAUTHORIZED);
}
$accessToken = AccessToken::updateOrCreate(
[ 'user_id' => $user->id ],
[ 'access_token' => Str::random(255) ]
);
RateLimiter::clear(request()->ip());
return response()->json([ 'access_token' => $accessToken->access_token ]);
} catch (\Throwable $th) {
throw $th;
}
}
Conclusion
This article will show you how to restrict user login by IP address when there is a failed attempt 3 times in a minute.
What if you want to restrict it forever?