This tutorial has a new version, check it out!

Switching Users / Impersonation

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

Switching Users / Impersonation

What’s that ROLE_ALLOWED_TO_SWITCH all about in security.yml. Symfony gives you the ability to actually change the user you’re logged in as. Ever have a client complaint you couldn’t replicate? Well now you can login as them without knowing their password. Now that is a Jedi mindtrick.

To activate this feature, add the switch_user key to your firewall:

# app/config/security.yml
    # ...
            # ...
            switch_user: ~

To use it, just add a ?_switch_user= query parameter to any page with the username you want to change to:

When we try it initially, we get the access denied screen. Our user needs ROLE_ALLOWED_TO_SWITCH to be able to do this. Add it to the ROLE_ADMIN hierarchy to get it:

# app/config/security.yml
    # ...
        # ...

When we refresh, you’ll see that the our username in the web debug toolbar has changed to darth. So cool! To switch back, use the _exit key:


Leave a comment!

  • 2016-12-09 Victor Bocharsky

    What ability do you mean exactly, could you clarify a bit? Facebook doesn't impersonate you like an other user - it just shows you how other user see your page. Do you need exactly this ability as Facebook does?

    When you go to the "?_switch_user=_exit" - system will switch you to the original ( i.e. your user) account, so it won't log out you completely.

  • 2016-12-09 Chaibi Alaa

    Thank you, do you know any solution to make users have such ability? Exactly like facebook one View profile as. In the case of this tuto does _exit closes the impersonated user and gets back to the needed user or does it simply gets completely logged out ?

  • 2016-12-09 Victor Bocharsky

    Hey Chaibi,

    Nope, you will have the same roles which the user has (the user which you impersonate), i.e. it's the same if you log in with credentials of other user, but... you know, you don't actually his credentials :) . So if the user doesn't have ROLE_ADMIN, you don't have it too after impersonation.


  • 2016-12-08 Chaibi Alaa

    Hi, thank you for the tuto. Just one question, are we kept logged as admin when we apply this ? Thanks