2

I'm using Symfony 3.4 and I'm working with the Impersonate user feature : https://symfony.com/doc/3.4/security/impersonating_user.html

I need when I impersonate an user to get the original user.. I don't know how can I do that.

During impersonation, the user is provided with a special role called ROLE_PREVIOUS_ADMIN, is there a way to change this role ?

For example if my original user is ROLE_ADMIN, the special role is ROLE_PREVIOUS_ADMIN, but if my original user is ROLE_SOMETHING, the custom role should be : ROLE_PREVIOUS_SOMETHING

I just need to have a way to get the original user or at least get his roles.

Thanks !

1 Answer 1

2

I found a solution :

public function isImpersonatorAdmin()
{
    $impersonatorUser = false;

    if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) {
        foreach ($this->security->getToken()->getRoles() as $role) {
            if ($role instanceof SwitchUserRole) {
                $impersonatorUser = $role->getSource()->getUser()->hasRole('ROLE_ADMIN');
                break;
            }
        }
    }

    return $impersonatorUser;
}

This function return true if the impersonator is ROLE_ADMIN.

1
  • SwitchUserRole is deprecated in favour of SwitchUserToken - since Symfony 4.3 you can fetch the original user with $impersonatorUser = $token->getOriginalToken()->getUser(); Feb 20, 2020 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.