Symfony2: How to restrict / deny access to certain routes by IP address?

拥有回忆 提交于 2019-12-07 03:13:10

问题


I'd like to disallow access to /login and /register if a client's IP address has been banned.

The (black-) list of banned IPs is stored in the database.

How can I solve this?


回答1:


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.yml
security:
    # ...
    access_control:
        - path: ^/(login|register)$
          allow_if: "request.getClientIp() not in @=service('access_manager').getBannedIPs()"



回答2:


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.



来源:https://stackoverflow.com/questions/29316277/symfony2-how-to-restrict-deny-access-to-certain-routes-by-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!