Symfony 2 - firewall and access control issue

2019-01-24 18:31发布

问题:

I've got a wired problem with the symfony 2 security component. Due to the fact that the {{ app.user }} object is only available within the secured area, I set the firewall pattern to ^/. Now I want to "unsecured" some pages, like registration. I've tried this by using access_control but it doesn't work.

Here is my security.yml

firewalls:
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false

    login:
        pattern:  ^/account/login$
        security: false

    account_area:
        pattern:    ^/
        form_login:
            check_path: /account/login_check
            login_path: /account/login
            default_target_path: /account
        remember_me:
            key:      blaBlubKey
            lifetime: 3600
            path:     /
            domain:   ~
        logout:
            path:   /account/logout
            target: /

access_control:
    #works
    - { path: ^/backend, roles: ROLE_USER }
    #works not
    - { path: ^/registration, roles: IS_AUTHENTICATED_ANONYMOUSLY }

Thanks in advance!

回答1:

USe anynymous directive in account_area:

account_area:
        pattern:    ^/
        anonymous: ~


回答2:

Worth mentioning is that the best practice here is to use only one firewall with access_control for login page. Why? What would You do if the logged user tries to access the /login page? You won't be able to check in controller if he is authenticated and redirect him, because the user will be authenticated to your main firewall, but not to the login firewall, as they are separate security systems.

Here is the security.yml that works great for me:

security:
    firewalls:
        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: true
            anonymous: ~ 
        secured_area:
            pattern:    ^/
            anonymous:  ~
            form_login:
                login_path:  /login
                check_path:  /login_check
                always_use_default_target_path: true
                default_target_path: /
            logout:
                path:   /logout
                target: /
    providers:
        main:
            entity: { class: Core\UserBundle\Entity\User, property: username }
    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin, roles: ROLE_SUPERADMIN }
        - { path: ^/user, roles: ROLE_USER }
        - { path: ^/, roles: IS_AUTHENTICATED_FULLY }