Symfony2 Secure by IP not working

2019-06-04 03:08发布

问题:

In my Symfony 2.3.1 Security YML, I have this line.

security.yml

access_control:
    - { path: ^/mysecurearea, roles: IS_AUTHENTICATED_ANONYMOUSLY, ip: 0.0.0.0 }

Based on this: http://symfony.com/doc/current/book/security.html

I was under the impression that this route and routes like it, e.g. /mysecurearea/something should only be accessible to a request from IP 0.0.0.0

Problem is, I can still access it.

Any ideas?

回答1:

So, all I wanted to do, was stop people from access an area, unless they had a valid IP. What I hadn't entirely appreciated, was that access_control can only give roles, rather than deny access. (Makes sense in hindsight.)

    - { path: ^/mysecurearea, roles: IS_AUTHENTICATED_ANONYMOUSLY, ip: 0.0.0.0 }
    - { path: ^/mysecurearea, roles: ROLE_NO_ACCESS }

So to achieve what I was looking for, I needed to add the additional line above. ROLE_NO_ACCESS doesn't actually exist. You just need to add some text there which is descriptive and note a valid role. Since it isn't a valid role, the requester can no longer access the area. It is a bit of a hack, but for my purposes, it does the job perfectly.



回答2:

My security.yml had some default entries that were somehow causing it to ignore the IP rules. I don't have any login functionality so my use case is quite simple.

Here is my entire security.yml that works for me in Symfony 2.3.6:

security:
    firewalls:
        anonymous:
            anonymous: ~

    providers:
        in_memory:
            memory:

    access_control:
        - { path: ^/foo, roles: IS_AUTHENTICATED_ANONYMOUSLY, ips: [127.0.0.1, ::1] }
        - { path: ^/foo, roles: ROLE_NO_ACCESS }

Just change the ^/foo path and the list of IPs.