Symfony2: How to restrict / deny access to certain routes by IP address?
Since symfony 2.4 you can use the Expression Language Component in your config-files.
Now implementing a simple IP check is easy:
- create a service (i.e.
access_manager
) with a method (i.e.getBannedIPs()
) that fetches the list of banned IPs from your storage layer - Add an expression to your security configuration that compares the returned array against the client's IP address
- That's it.
example
# app/config/security.ymlsecurity: # ... access_control: - path: ^/(login|register)$ allow_if: "request.getClientIp() not in @=service('access_manager').getBannedIPs()"
Use controllers events (preferred)
You can subscribe to events on registration controller.
For registration, you can subscribe to REGISTRATION_INITIALIZE
event.
Here is the doc for controller events.
Overriding controller methods
The second solution is to override login and register controller methods but you will have to duplicate all code of the login/register action.