Symfony security: authentication, authorization and security.yaml

Security in Symfony happens in two steps: the firewall authenticates, establishing who makes the request, then authorization decides what they are allowed to do.

# config/packages/security.yaml
security:
    providers:
        employes: { entity: { class: App\Entity\Employe, property: email } }
    firewalls:
        main:
            provider: employes
            form_login: { login_path: app_connexion, check_path: app_connexion }
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
#[IsGranted('PLAT_MODIFIER', 'plat')] // a voter decides, based on the dish and the user
public function modifier(Plat $plat): Response { /* … */ }

Everything starts from security.yaml: the provider finds the user, the firewall chooses how they prove their identity (form, login link, API token, second factor), and passwords are only ever stored hashed. Authorization comes next: access_control protects URLs by role, role_hierarchy avoids repeating roles, #[IsGranted], isGranted() and is_granted() ask the question as close to the code as possible, and a voter decides when the permission depends on the object. The trap: mixing the two up. A visitor who isn't logged in is sent to the login page, a logged-in user without the permission gets a 403; answering 403 to someone who only needs to give a proof again, their password or a code, blocks them without telling them what to do.

The exercises focus on what's new in Symfony 8.2: requiring an SMS code before a transfer, asking for the password again before sensitive pages, asking for the right factor again instead of a 403, a login link that keeps its destination, roles by family with wildcards, and validation that depends on the user's permissions.

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

In the tracks

In Practice

Related concepts

TwigCSRFHttpFoundationFormsN+1 queriesFirewallRoutingHttpKernel