Symfony 8.2 is packed with new security features, such as OpenID Connect login and sudo mode. This article showcases other smaller but useful improvements of the Security component.

Checking Users Again on Each Request

Kevin Bond
Contributed by Kevin Bond in #66136 and #66117

User checkers reject disabled, locked or expired accounts, but they only run when users log in. If an administrator disables an account while its user is logged in, that user keeps browsing the application until their session ends.

Symfony 8.2 adds a user_checker_on_refresh firewall option that runs the user checker again whenever the user is refreshed from the session:

1
2
3
4
5
6
# config/packages/security.yaml
security:
    firewalls:
        main:
            user_checker: App\Security\UserChecker
            user_checker_on_refresh: true

If the checker throws an exception, Symfony logs the user out on that same request. The option is disabled by default because the checker now runs on every request of the firewall, so make sure it's fast and has no side effects. When impersonating a user, only checkPostAuth() is called, as it happens when switching to that user.

This option relies on the new CheckRefreshedUserEvent, dispatched after Symfony compares the user stored in the session with the one reloaded from the user provider. Listen to it to add your own reasons to log users out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/EventListener/BannedUserListener.php
namespace App\EventListener;

use App\Entity\User;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Security\Core\Exception\LockedException;
use Symfony\Component\Security\Http\Event\CheckRefreshedUserEvent;

final class BannedUserListener
{
    #[AsEventListener]
    public function onCheckRefreshedUser(CheckRefreshedUserEvent $event): void
    {
        $user = $event->getRefreshedUser();

        if ($user instanceof User && $user->isBanned()) {
            $event->setUserChanged(true, new LockedException());
        }
    }
}

The exception is later available via TokenDeauthenticatedEvent::getException(), so you can tell users why they were logged out.

Checking the Permissions of Guests

Andreas Schempp
Contributed by Andreas Schempp in #61938

The isGrantedForUser() method checks the permissions of any user, not only the one who is logged in. However, it required a user object, so you couldn't use it to know what anonymous visitors are allowed to do. In Symfony 8.2, pass null as the user to run your voters against a guest (a token with no user and no roles):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/Sitemap/SitemapGenerator.php
namespace App\Sitemap;

use Symfony\Component\Security\Core\Authorization\GuestAuthorizationCheckerInterface;

class SitemapGenerator
{
    public function __construct(
        private GuestAuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    public function generate(iterable $posts): string
    {
        foreach ($posts as $post) {
            // only list the posts that anyone can see
            if (!$this->authorizationChecker->isGrantedForUser(null, 'view', $post)) {
                continue;
            }

            // ...
        }

        // ...
    }
}

The new GuestAuthorizationCheckerInterface extends UserAuthorizationCheckerInterface, which keeps accepting only users. The Security helper and the is_granted_for_user() and access_decision_for_user() Twig functions accept null too:

1
2
3
{% if not is_granted_for_user(null, 'view', post) %}
    <span class="badge">Members only</span>
{% endif %}

Mixing LDAP and Local Users

Nicolas Grekas
Contributed by Nicolas Grekas in #64976

When using LDAP authentication, Symfony checks the password of every user of the firewall against the LDAP server. That's a problem when the firewall uses a chain provider that also loads users from other sources, like your database: their passwords are sent to the LDAP server and their logins fail.

Symfony 8.2 adds an ldap_users_only option to the form_login_ldap, json_login_ldap and http_basic_ldap authenticators. When enabled, only the users loaded as LdapUser objects are checked against the LDAP server; the others are checked with their password hasher, as in a regular login:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# config/packages/security.yaml
security:
    providers:
        ldap_users:
            ldap:
                # ...
        local_users:
            entity: { class: App\Entity\User, property: email }
        all_users:
            chain:
                providers: [ldap_users, local_users]

    firewalls:
        main:
            provider: all_users
            form_login_ldap:
                # ...
                ldap_users_only: true

Symfony throws an exception when building the container if you enable this option and none of the user providers of the firewall is an LDAP provider.

Hiding Which Usernames Exist

Nicolas Grekas
Contributed by Nicolas Grekas in #67803

Hashing a password is slow on purpose. Since Symfony only hashed the submitted password when the user existed, logins with an unknown username failed faster than logins with a wrong password. Attackers could measure that difference to find out which usernames exist in your application.

In Symfony 8.2, logins with an unknown username hash the submitted password too, so both take about the same time. The same happens for:

  • users that have no password;
  • users rejected by the user checker (e.g. disabled accounts), but only when the expose_security_errors option is none (its default value);
  • failed LDAP logins on firewalls that enable the ldap_users_only option explained above.

Symfony skips this when expose_security_errors is all, because the error messages already tell whether the user exists. This works out of the box, but these failed logins now use as much CPU as the others, so use login throttling to limit how many of them a client can send.

Keeping the Referer After a Failed Login

Nicolas Grekas
Contributed by Nicolas Grekas in #67041

The use_referer option of the login authenticators redirects users to the page they came from after logging in. However, if their first attempt failed, they were sent back to the login page, which became the referer of the second attempt. A successful retry then redirected to the default target path instead of the original page.

In Symfony 8.2, when use_referer is enabled, a failed login saves the referer as the target path of the firewall (unless there's one saved already), so the next successful login redirects there. Only referers of the same host are saved, and never the login page itself.

Deprecated Access Control Rules with Multiple Attributes

Pascal CESCON Mathieu Lechat
Contributed by Pascal CESCON and Mathieu Lechat in #65827 and #65056

Access control rules can define several roles, or both roles and allow_if. They are the only place where Symfony checks several security attributes in a single access decision; everywhere else (isGranted(), #[IsGranted], etc.) it checks one attribute at a time. Symfony 8.2 deprecates both configurations to remove this special case. Use a single allow_if expression instead:

1
2
3
4
5
# config/packages/security.yaml
  security:
      access_control:
-         - { path: ^/admin, roles: [ROLE_ADMIN, ROLE_SUPPORT] }
+         - { path: ^/admin, allow_if: 'is_granted("ROLE_ADMIN") or is_granted("ROLE_SUPPORT")' }

Another option is to define a role in the role hierarchy that the other roles include and check only that one. Splitting the rule into one rule per role doesn't work, because Symfony only applies the first rule that matches the request.

As a result, passing more than one attribute to AccessDecisionManager::decide() is deprecated in all cases, and its $allowMultipleAttributes argument will be removed in Symfony 9.0.

Deprecated Password Migrations to Legacy Hashers

Nicolas Grekas
Contributed by Nicolas Grekas in #67025

The migrate_from option of password hashers lists the previous hashers of your application, so users can keep logging in with their old password hash while Symfony rehashes it with the new algorithm. This only works when the new hasher asks for that rehash, and the plaintext, pbkdf2 and message digest (sha512, md5, etc.) hashers never do. With them, migrate_from did nothing and no error told you about it.

Symfony 8.2 deprecates using migrate_from in those hashers. Migrate to auto instead (or to a custom hasher whose needsRehash() method can return true):

1
2
3
4
5
6
7
8
9
10
11
12
13
# config/packages/security.yaml
  security:
      password_hashers:
          legacy_md5:
              algorithm: md5
+         legacy_sha512:
+             algorithm: sha512

          App\Entity\User:
-             algorithm: sha512
-             migrate_from: [legacy_md5]
+             algorithm: auto
+             migrate_from: [legacy_md5, legacy_sha512]

Legacy hashers are still valid as the hashers you migrate from, as shown above.

Switching Users with POST Requests and CSRF Tokens

Kevin Bond
Contributed by Kevin Bond in #64879

User impersonation is triggered by adding a _switch_user query parameter to any URL of the firewall. That's convenient, but it means that a plain GET request changes who you are in the application. In Symfony 8.2, the switch_user option accepts a path to restrict impersonation to a dedicated route, which you can declare as POST-only, and it can require a CSRF token:

1
2
3
4
5
6
7
8
# config/packages/security.yaml
security:
    firewalls:
        main:
            # ...
            switch_user:
                path: app_switch_user # a route name or a path
                enable_csrf: true

Then, define that route and restrict it to POST requests. It needs no controller because the firewall handles the request:

1
2
3
4
# config/routes.yaml
app_switch_user:
    path: /switch-user
    methods: [POST]

As with the new logout form, this requires a form instead of a link, so Symfony 8.2 adds the impersonation_form() and impersonation_exit_form() Twig functions. They return the form action and its hidden fields (user identifier, CSRF token and the optional path to redirect to afterwards):

1
2
3
4
5
6
7
8
9
{% set impersonate = impersonation_form(user.userIdentifier, app.request.pathInfo) %}

<form method="post" action="{{ impersonate.action }}">
    {% for name, value in impersonate.fields %}
        <input type="hidden" name="{{ name }}" value="{{ value }}">
    {% endfor %}

    <button>Impersonate {{ user.userIdentifier }}</button>
</form>

If you don't set the path option, impersonation works as before.

Published in #Living on the edge