New in Symfony 4.3: Deprecated the Role and SwitchUserRole classes

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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();
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments

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