English spoken conference

Symfony 5: The Fast Track

A new book to learn about developing modern Symfony 5 applications.

Support this project

New in Symfony 4.3: Deprecated the Role and SwitchUserRole classes

Contributed by
Christian Flothmann
in #22048.

A long-standing goal of Symfony is to simplify certain parts of the security system. In Symfony 3.3 we deprecated the RoleInterface and in Symfony 4.1 we deprecated the AdvancedUserInterface. In Symfony 4.3 we've deprecated the Role and SwitchUserRole classes.

In practice there are few real benefits of using objects instead of strings to represent roles. Eventually it only led to overhead because you had to call Role::getRole() to get the actual string representing the role.

If your app uses the full-stack Symfony framework, you probably don't need to change anything because you are already defining roles with raw strings. If you use the standalone Security component, you need to refactor any code dealing with Role classes (or define your own Role class to keep using classes).

If you are impersonating users in your app, you need to refactor any code that uses SwitchUserRole to use instead the new SwitchUserToken:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// BEFORE
use Symfony\Component\Security\Core\Role\SwitchUserRole;

if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) {
    foreach ($this->security->getToken()->getRoles() as $role) {
        if ($role instanceof SwitchUserRole) {
            $impersonatorUser = $role->getSource()->getUser();
            break;
        }
    }
}

// AFTER
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;

$token = $this->security->getToken();
if ($token instanceof SwitchUserToken) {
    $impersonatorUser = $token->getOriginalToken()->getUser();
}

New in Symfony 4.3: Deprecated the Role and SwitchUserRole classes symfony.com/blog/new-in-symfony-4-3-deprecated-the-role-and-switchuserrole-classes

Tweet this

Comments

Finally! I can't wait to see more changes in the user interface ! :)

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.