Switch user sessions using Account Switcher service | Drupal 8

Switch user sessions using Account Switcher service

Submitted by editor on Wed, 05/23/2018 - 22:12
Question

How to switch user sessions using account switcher (account_switcher) service ?

Example:

use Drupal\Core\Session\UserSession;
//
// Call the account switcher service
$accountSwitcher = \Drupal::service('account_switcher');
// Switch to the admin user
$accountSwitcher->switchTo(new \Drupal\Core\Session\UserSession(['uid' => 1]));
//
// Your Code Hear...
//
// Switch back to old session.
$accountSwitcher->switchBack();

Add new comment