Switch user session programmatically I'm trying to switch user session thanks to Drupal Switch. I want to do this so that when I have a certain role, I can switch to another user account to check some data from the user i choose to switch.

My routing :

double_vue.page_double_vue:
    path: '/double-vue'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::doubleVue'
        _title: 'Double vue'
    requirements:
        _permission: 'access content'
double_vue.switched_user:
    path: '/double-vue/{userSwitchedID}'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::switchUser'
        _title: 'UserSwitched'
    requirements:
        _permission: 'access content'


My view : 

&lt;a class="btn btn-primary btn-xs" href="{{ path('double_vue.switched_user', { 'userSwitchedID': "15" }) }}"&gt;switch&lt;/a&gt;


My function : 

  public function switchUser($userSwitchedID){
    $accountSwitcher = \Drupal::service('account_switcher');
    $account = \Drupal\user\Entity\User::load($userSwitchedID);
    return $accountSwitcher-&gt;switchTo($account);
  }


When I click on my to link to switch to another user, I have this error in my logs :


  The controller must return a response
  (Object(Drupal\Core\Session\AccountSwitcher) given)


If I remove the return, I have this :


  The controller must return a response (null given)


How can I fix that so that I can switch to another user account ?
So first, the account switcher is for a temporary switch in the same request, to execute a specific thing as another user, it can't be used for what you want.

What Masquerade does is a lot more complicated and I don't understand why you don't just use that. Masquerade automatically adds itself to the user operations, so if you build a view that lists your users with the operations field then you will have exactly what you want to do.


  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.