Change record status: 
Project: 
Introduced in branch: 
8.0.x
Introduced in version: 
8.0.0-BETA4
Description: 

The method of switching between user accounts safely has changed from Drupal 7 and Drupal 8.0.0-beta3. This is also documented in more depth on the Develop for Drupal handbook page, "Safely Impersonating Another User".

In D7:

You must save the user session before changing the global user object.

global $user;
$original_user = $user;
$old_state = drupal_save_session();
drupal_save_session(FALSE);
$user = user_load(1);

// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
drupal_save_session($old_state);

// From here on the $user is back to normal so it's OK for the session to be saved

In D8:

You can now use the Account Switcher service to switch to a different user account and switch back. It is not necessary to call PHP session handling functions anymore as this is done by the service.

The core Cron service will do this by default before calling cron handlers and processing queues.

  // Retrieve the account switcher service. Ideally you should inject the account_switcher service into your class.
  $accountSwitcher = Drupal::service('account_switcher');
  $accountSwitcher->switchTo(new Drupal\Core\Session\AnonymousUserSession());
  
  // Take your action here. If your code fails, then you should catch an exception
  // and switch back (see below).

  // Restore user account.
  $accountSwitcher->switchBack();
Impacts: 
Module developers