One of my current projects is using JWT Authentication for an API built on Symfony (shocker, I know). One of the things I wanted to build into this was a limiter on the number of “login” attempts for the API that would lock someone out for x minutes after n failed attempts; mirroring typical traditional form login behavior.

This was accomplished with the following components:

  • Separate non-entity-driven database table
  • Parameters for defining the number of minutes to lock and the number of attempts before triggering a a lock.
  • A simple handler to check our table and do some simple maintenance and querying.

Separate non-entity-driven database table

The database table to track login attempts needed to be separate from a Doctrine (the ORM in this case) entity because a failed attempt naturally did not map to a real User. Similarly, we didn’t want to track ip_addr of logged in users because we are not Vizio. So, that being said, we created a very simple database table to track login attempts by ip_addr:


Again in this case, we wanted to parameterize the values we used to determine the number of attempts, and the number of minutes a user was locked out from attempting to login. With Symfony this is a simple addition to the parameters file.

It’s important to note that timezone is very important here for comparing dates (later), so make sure when you define this (or if you ever change it) that you clear out the login_attempts table as well.


Most importantly, we had to build a simple handler to manage our queries and maintenance actions. Ultimately, this is where the magic happens but the most important part is still last where we handle the actual logic in our Authentication controller (see below). However, this handler does the heavy lifting, and does have some room for improvement, particularly with Unit Testing.

Define LoginAttemptHandler as a Service

Symfony needs to understand this handler is a service, so we can use it in our Controller (next).

Handle Login Attempts in our Authentication Controller

Now, every time there is a JWT Token request, we have a slight amount of extra overhead to verify login attempts in our Controller.


Categories: Random