Symfony 8.2 New Published on

A route that picks its firewall

The firewall option of #[Route] hands a route to a firewall without touching its pattern, and entry_point_path sends anonymous users to the login page, with no class to write.

Topics covered: SecurityFirewallRouting

New in Symfony 8.2 (in development). A firewall applies to the requests its pattern (or its request_matcher) recognises. In an application split into modules, each module that wanted the API firewall had to register in the pattern, right in security.yaml.

The firewall in the route

The route's new firewall option names the firewall that guards it:

#[Route('/api/orders', name: 'api_orders', firewall: 'api_jwt')]
public function orders(): Response

The named firewall is used instead of the one the patterns would have picked. An unknown name throws an exception, rather than silently falling back to another firewall. access_control rules apply as usual, and debug:router shows the choice under _firewall.

Redirecting anonymous users with no class to write

Some authenticators, such as json_login, don't know where to send an anonymous user: they get a 401. You needed an AuthenticationEntryPointInterface class to redirect them. The new entry_point_path option is enough:

security:
    firewalls:
        main:
            json_login:
                check_path: login_api
            entry_point_path: login

It takes a path, an absolute URL or a route name, like login_path. In a firewall with a session, Symfony keeps the requested address in the session, so you can go back to it after logging in. It can't be combined with entry_point.

Your task

The “partners” module exposes /partners/stock, reserved for partners (the ROLE_PARTNER role), who log in with a token (Authorization: Bearer partner-token). But the “api” firewall only guards ^/api/: the route falls into “main”, which ignores the token.

  1. Have /partners/stock guarded by the “api” firewall, without touching its pattern.
  2. An anonymous user opening /account gets a 401: send them to the login page instead.

Where the feature comes from: the original pull request.