Skip to content

Add example for using a voter to restrict switch_user #9353

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions security/impersonating_user.rst
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,68 @@ setting:
),
));

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.

.. versionadded:: 4.1
The target user was added as the voter subject parameter in Symfony 4.1.

Create the voter class::

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;
}
}

Thanks to service autoconfiguration and autowiring, this new voter is automatically
registered as a service and tagged as a security voter.

Now a user who has the ``ROLE_SWITCH_TO_CUSTOMER`` role can switch to a user who explicitly has the
``ROLE_CUSTOMER`` role, but not other users.

Events
------

Expand Down