@@ -98,11 +98,17 @@ to show a link to exit impersonation:
9898Finding the Original User
9999-------------------------
100100
101+ versionadded:: 4.3
102+
103+ The ``SwitchUserToken `` class was introduced in Symfony 4.3.
104+
101105In some cases, you may need to get the object that represents the impersonator
102- user rather than the impersonated user. Use the following snippet to iterate
103- over the user's roles until you find one that is a ``SwitchUserRole `` object::
106+ user rather than the impersonated user. When a user is impersonated the token
107+ stored in the token storage will be a ``SwitchUserToken `` instance. Use the
108+ following snippet to obtain the original token which gives you access to
109+ the impersonator user::
104110
105- use Symfony\Component\Security\Core\Role\SwitchUserRole;
111+ use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken
106112 use Symfony\Component\Security\Core\Security;
107113 // ...
108114
@@ -119,14 +125,13 @@ over the user's roles until you find one that is a ``SwitchUserRole`` object::
119125 {
120126 // ...
121127
122- if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) {
123- foreach ($this->security->getToken()->getRoles() as $role) {
124- if ($role instanceof SwitchUserRole) {
125- $impersonatorUser = $role->getSource()->getUser();
126- break;
127- }
128- }
128+ $token = $this->security->getToken();
129+
130+ if ($token instanceof SwitchUserToken) {
131+ $impersonatorUser = $token->getOriginalToken()->getUser();
129132 }
133+
134+ // ...
130135 }
131136 }
132137
@@ -221,24 +226,17 @@ Create the voter class::
221226 }
222227
223228 if (in_array('ROLE_CUSTOMER', $subject->getRoles())
224- && $this->hasSwitchToCustomerRole($token )) {
229+ && in_array('ROLE_SWITCH_TO_CUSTOMER', $token->getRoleNames(), true )) {
225230 return true;
226231 }
227232
228233 return false;
229234 }
235+ }
230236
231- private function hasSwitchToCustomerRole(TokenInterface $token)
232- {
233- foreach ($token->getRoles() as $role) {
234- if ($role->getRole() === 'ROLE_SWITCH_TO_CUSTOMER') {
235- return true;
236- }
237- }
237+ .. versionadded :: 4.3
238238
239- return false;
240- }
241- }
239+ The ``getRoleNames() `` method was introduced in Symfony 4.3.
242240
243241To enable the new voter in the app, register it as a service and
244242:doc: `tag it </service_container/tags >` with the ``security.voter ``
0 commit comments