Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
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!

What PHP libraries does this tutorial use?

// composer.json
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "~2.4", // v2.4.2
        "doctrine/orm": "~2.2,>=2.2.3", // v2.4.2
        "doctrine/doctrine-bundle": "~1.2", // v1.2.0
        "twig/extensions": "~1.0", // v1.0.1
        "symfony/assetic-bundle": "~2.3", // v2.3.0
        "symfony/swiftmailer-bundle": "~2.3", // v2.3.5
        "symfony/monolog-bundle": "~2.4", // v2.5.0
        "sensio/distribution-bundle": "~2.3", // v2.3.4
        "sensio/framework-extra-bundle": "~3.0", // v3.0.0
        "sensio/generator-bundle": "~2.3", // v2.3.4
        "incenteev/composer-parameter-handler": "~2.0", // v2.1.0
        "doctrine/doctrine-fixtures-bundle": "~2.2.0", // v2.2.0
        "ircmaxell/password-compat": "~1.0.3", // 1.0.3
        "phpunit/phpunit": "~4.1" // 4.1.0