@@ -98,11 +98,17 @@ to show a link to exit impersonation:
98
98
Finding the Original User
99
99
-------------------------
100
100
101
+ versionadded:: 4.3
102
+
103
+ The ``SwitchUserToken `` class was introduced in Symfony 4.3.
104
+
101
105
In 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::
104
110
105
- use Symfony\Component\Security\Core\Role\SwitchUserRole;
111
+ use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken
106
112
use Symfony\Component\Security\Core\Security;
107
113
// ...
108
114
@@ -119,14 +125,13 @@ over the user's roles until you find one that is a ``SwitchUserRole`` object::
119
125
{
120
126
// ...
121
127
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();
129
132
}
133
+
134
+ // ...
130
135
}
131
136
}
132
137
@@ -221,24 +226,17 @@ Create the voter class::
221
226
}
222
227
223
228
if (in_array('ROLE_CUSTOMER', $subject->getRoles())
224
- && $this->hasSwitchToCustomerRole($token )) {
229
+ && in_array('ROLE_SWITCH_TO_CUSTOMER', $token->getRoleNames(), true )) {
225
230
return true;
226
231
}
227
232
228
233
return false;
229
234
}
235
+ }
230
236
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
238
238
239
- return false;
240
- }
241
- }
239
+ The ``getRoleNames() `` method was introduced in Symfony 4.3.
242
240
243
241
To enable the new voter in the app, register it as a service and
244
242
:doc: `tag it </service_container/tags >` with the ``security.voter ``
0 commit comments