How to Impersonate a User
Edit this pageWarning: You are browsing the documentation for Symfony 4.1, which is no longer maintained.
Read the updated version of this page for Symfony 6.1 (the current stable version).
How to Impersonate a User
Sometimes, it's useful to be able to switch from one user to another without having to log out and log in again (for instance when you are debugging something a user sees that you can't reproduce).
Caution
User impersonation is not compatible with some authentication mechanisms
(e.g. REMOTE_USER
) where the authentication information is expected to be
sent on each request.
Impersonating the user can be done by activating the switch_user
firewall listener:
- YAML
- XML
- PHP
1 2 3 4 5 6 7 8
# config/packages/security.yaml
security:
# ...
firewalls:
main:
# ...
switch_user: true
To switch to another user, add a query string with the _switch_user
parameter and the username (or whatever field our user provider uses to load users)
as the value to the current URL:
1
http://example.com/somewhere?_switch_user=thomas
To switch back to the original user, use the special _exit
username:
1
http://example.com/somewhere?_switch_user=_exit
This feature is only available to users with a special role called ROLE_ALLOWED_TO_SWITCH
.
Using role_hierarchy is a great way to give this
role to the users that need it.
Knowing When Impersonation Is Active
During impersonation, the user is provided with a special role called
ROLE_PREVIOUS_ADMIN
. In a template, for instance, this role can be used
to show a link to exit impersonation:
1 2 3
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
<a href="{{ path('homepage', {'_switch_user': '_exit'}) }}">Exit impersonation</a>
{% endif %}
Finding the Original User
In some cases, you may need to get the object that represents the impersonator
user rather than the impersonated user. Use the following snippet to iterate
over the user's roles until you find one that is a SwitchUserRole
object:
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 27
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\Security;
// ...
public class SomeService
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function someMethod()
{
// ...
if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) {
foreach ($this->security->getToken()->getRoles() as $role) {
if ($role instanceof SwitchUserRole) {
$impersonatorUser = $role->getSource()->getUser();
break;
}
}
}
}
}
Controlling the Query Parameter
This feature needs to be available only to a restricted group of users.
By default, access is restricted to users having the ROLE_ALLOWED_TO_SWITCH
role. The name of this role can be modified via the role
setting. You can
also adjust the query parameter name via the parameter
setting:
- YAML
- XML
- PHP
1 2 3 4 5 6 7 8
# config/packages/security.yaml
security:
# ...
firewalls:
main:
# ...
switch_user: { role: ROLE_ADMIN, parameter: _want_to_be_this_user }
Limiting User Switching
If you need more control over user switching, but don't require the complexity
of a full ACL implementation, you can use a security voter. For example, you
may want to allow employees to be able to impersonate a user with the
ROLE_CUSTOMER
role without giving them the ability to impersonate a more
elevated user such as an administrator.
4.1
The target user was added as the voter subject parameter in Symfony 4.1.
Create the voter class:
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class SwitchToCustomerVoter extends Voter
{
protected function supports($attribute, $subject)
{
return in_array($attribute, ['ROLE_ALLOWED_TO_SWITCH'])
&& $subject instanceof UserInterface;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous or if the subject is not a user, do not grant access
if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
return false;
}
if (in_array('ROLE_CUSTOMER', $subject->getRoles())
&& $this->hasSwitchToCustomerRole($token)) {
return true;
}
return false;
}
private function hasSwitchToCustomerRole(TokenInterface $token)
{
foreach ($token->getRoles() as $role) {
if ($role->getRole() === 'ROLE_SWITCH_TO_CUSTOMER') {
return true;
}
}
return false;
}
}
To enable the new voter in the app, register it as a service and
tag it with the security.voter
tag. If you're using the
default services.yaml configuration,
this is already done for you, thanks to autoconfiguration.
Now a user who has the ROLE_SWITCH_TO_CUSTOMER
role can switch to a user who
has the ROLE_CUSTOMER
role, but not other users.
Events
The firewall dispatches the security.switch_user
event right after the impersonation
is completed. The SwitchUserEvent is
passed to the listener, and you can use this to get the user that you are now impersonating.
The Making the Locale "Sticky" during a User's Session article does not update the locale when you impersonate a user. If you do want to be sure to update the locale when you switch users, add an event subscriber on this event:
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 27 28 29 30
// src/EventListener/SwitchUserSubscriber.php
namespace App\EventListener;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\SecurityEvents;
class SwitchUserSubscriber implements EventSubscriberInterface
{
public function onSwitchUser(SwitchUserEvent $event)
{
$request = $event->getRequest();
if ($request->hasSession() && ($session = $request->getSession)) {
$session->set(
'_locale',
// assuming your User has some getLocale() method
$event->getTargetUser()->getLocale()
);
}
}
public static function getSubscribedEvents()
{
return [
// constant for security.switch_user
SecurityEvents::SWITCH_USER => 'onSwitchUser',
];
}
}
That's it! If you're using the default services.yaml configuration,
Symfony will automatically discover your service and call onSwitchUser
whenever
a switch user occurs.
For more details about event subscribers, see Events and Event Listeners.