access_control in Symfony: protecting URLs by role

The access_control key of Symfony security maps URL patterns to the required roles: the first rule that matches the path decides on access.

security:
    # The boss also has all the rights of a cook.
    role_hierarchy:
        ROLE_PATRON: [ROLE_CUISINIER]

    # Only the first matching rule applies.
    access_control:
        - { path: ^/cuisine, roles: ROLE_CUISINIER }
        # A "^/" PUBLIC_ACCESS rule placed above would open the kitchen too.

Each rule combines a path, a regular expression, with methods, host or ip if needed, and the required roles. Symfony reads them in order and stops at the first that matches: an anonymous visitor is sent to the login page, a logged-in user without the role gets a 403. role_hierarchy avoids repeating the roles of an account that includes others. The trap: the order of the rules. A ^/ rule with PUBLIC_ACCESS written first matches every URL and silences the ones after it. Likewise, a misspelled role is never a configuration error: it's a role nobody has.

The exercises have you close the tavern's kitchen to the public, with an in-memory user whose password is hashed, form login and a rule on /cuisine, then investigate a security configuration "hardened" by Pipin, where customers walk into the kitchen and the boss no longer sees the link that leads there.

2 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

FirewallDebuggingrole_hierarchyVoter