Nicolas Grekas
Contributed by Nicolas Grekas in #33676

In Symfony's Security component, firewalls configure how your users will be able to authenticate (e.g. using a login form, an API token, etc). Firewalls also configure which URLs they cover and whether anonymous users are allowed to browse those URLs or not:

1
2
3
4
5
6
7
8
# config/packages/security.yaml
security:
    # ...
    firewalls:
        main:
            pattern: ^/
            anonymous: ~
            # ...

When a stateful firewall is configured, a user token is always created from the session for every request, no matter if the user is actually used or not by the application. This means that all those responses are uncacheable (because they use the session).

In Symfony 4.4, firewalls can define lazy as the value of their anonymous configuration option:

1
2
3
4
5
6
7
8
# config/packages/security.yaml
security:
    # ...
    firewalls:
        main:
            pattern: ^/
            anonymous: lazy
            # ...

This tells Symfony to only load the user (and start the session) if the application actually access the user object (e.g. via a is_granted() call in a template or a isGranted() call in a controller or service). This means that all those URLs/actions that don't need the user will now be public and cacheable, improving the performance of your application.

Published in #Living on the edge