Limit login attempts in Symfony 5+

Oleksii Marakhin
2 min readApr 9, 2024

--

Follow this article to create a login limit for your application!

In Symfony, we have a way to prevent someone from a single IP address from testing passwords over and over again on different emails. This mechanism is a great way to protect your web application from brute-force attacks.

Image source: https://www.varonis.com/blog/brute-force-attack

But I need to mention, that this functionality was introduced in Symfony 5.2, so be sure you are using version 5.2 or above.

Step 1

To implement this cool functionality, we will need a Rate Limiter component, you can install it by executing the next command:

composer require symfony/rate-limiter

The rate-limiter package will also install a package named symfony/lock. This package has a recipe, meaning it has a script that is being executed when the package download is finished.

You will notice the config/packages/lock.yaml was created and the .env file was modified.

#########

If your Symfony version is 6.2 or above symfony/lock package is no longer needed, so the lock.yaml won’t be created.

#########

We will definitely need to store the number of login attempts somewhere. That’s what symfony/lock package took care of us and created the next .env variable:

LOCK_DSN=semaphore

Locks are used to guarantee exclusive access to some shared resources. In Symfony applications, you can use locks for example to ensure that a command is not executed more than once at the same time (on the same or different servers). Or like in this example, we use it to limit login attempts.

And semaphore uses Semaphore functions.

Step 2

Under the firewalls section in the file config/packages/security.yaml you need to add login_throttling configuration and assign it a value true:

security:
firewalls:
default:
login_throttling: true

And that’s all! By default, this feature allows 5 login attempts per 1 minute. Take a look at the next step if you want to know how to change default values!

Step 3 — let’s customize!

Let’s customize it a bit, as far as every one of us might need different restrictions.

You can edit the maximum login attempts per 1 minute:

login_throttling:
max_attempts: 2

You can set a new interval:

login_throttling:
interval: '20 minutes'

Or you can customize it even more by using your rate limiter:

login_throttling:
## you'll need to put a service id here
limiter: app.login_rate_limiter

How to check if changes were applied? Execute in the terminal the next command:

symfony console debug:config security

Search for login_throttling and you will see if changes were applied!

--

--

Oleksii Marakhin

I'm a Software Engineer, I try to constantly develop my skills.