Search code examples
phpsymfonysymfony4symfony-security

Is the firewall declaration order significant in security.yaml?


In my project, I have 2 providers and 2 firewalls.

Is there an order to respect when declaring your firewalls? In my example, if I start with admin and then user, it works perfectly.

If I do the opposite, I can not connect with the admin anymore.

Why does this happen?

providers:
    app_user_provider:
        entity:
            class: App\Entity\User
            property: email
    app_user_admin_provider:
        entity:
            class: App\Entity\Useradmin
            property: email

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    admin:
        anonymous: true
        pattern: ^/admin
        provider: app_user_admin_provider
        guard:
            authenticators:
                - App\Security\AdminFormAuthenticator
        logout:
            path: /admin/logout
            target: home
    user:
        anonymous: true
        pattern: ^/
        provider: app_user_provider
        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
        logout:
            path: /profile/logout
            target: home

access_control:
    - { path: ^/admin$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/profile, roles: ROLE_USER }

role_hierarchy:
    ROLE_ADMIN: ROLE_USER

Solution

  • The order is significant because when making a request, the first matched firewall will be the one used.

    If the patterns for the first firewall is ^/, then it will match all requests, and no other firewall will be evaluated.

    If the patterns for the first firewall is ^/admin, the "admin" firewall will be used for /admin/ requests, and the "user" firewall will be used for any other request that does not match ^/admin