diff --git a/core/authorize.php b/core/authorize.php
index dbab02f..7e6be73 100644
--- a/core/authorize.php
+++ b/core/authorize.php
@@ -50,8 +50,10 @@
  * @return bool
  *   TRUE if the current user can run authorize.php, and FALSE if not.
  */
-function authorize_access_allowed() {
-  return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates');
+function authorize_access_allowed(Request $request) {
+  $account = \Drupal::service('authentication')->authenticate($request);
+  \Drupal::service('current_user')->setAccount($account);
+  return Settings::get('allow_authorize_operations', TRUE) && $account->hasPermission('administer software updates');
 }
 
 try {
@@ -79,7 +81,7 @@ function authorize_access_allowed() {
 $show_messages = TRUE;
 
 $response = new Response();
-if (authorize_access_allowed()) {
+if (authorize_access_allowed($request)) {
   // Load both the Form API and Batch API.
   require_once __DIR__ . '/includes/form.inc';
   require_once __DIR__ . '/includes/batch.inc';
diff --git a/core/core.services.yml b/core/core.services.yml
index 5080841..949112a 100644
--- a/core/core.services.yml
+++ b/core/core.services.yml
@@ -578,7 +578,7 @@ services:
     arguments: ['@url_generator', '@module_handler']
   router:
     class: Drupal\Core\Routing\AccessAwareRouter
-    arguments: ['@router.no_access_checks', '@access_manager', '@current_user']
+    arguments: ['@router.no_access_checks', '@access_manager', '@authentication', '@current_user']
   router.dynamic:
     class: Symfony\Cmf\Component\Routing\DynamicRouter
     arguments: ['@router.request_context', '@router.matcher', '@url_generator']
@@ -701,7 +701,7 @@ services:
   route_enhancer.lazy_collector:
     class: Drupal\Core\Routing\LazyRouteEnhancer
     tags:
-      - { name: non_lazy_route_enhancer, priority: 5000 }
+      - { name: non_lazy_route_enhancer }
     parent: container.trait
   route_enhancer_subscriber:
     class: Drupal\Core\EventSubscriber\RouteEnhancerSubscriber
@@ -717,8 +717,8 @@ services:
   route_enhancer.authentication:
     class: Drupal\Core\Routing\Enhancer\AuthenticationEnhancer
     tags:
-      - { name: route_enhancer, priority: 1000 }
-    arguments: ['@authentication', '@current_user']
+      - { name: non_lazy_route_enhancer, priority: 1000 }
+    arguments: ['@authentication', '@current_user', '@request_stack']
   route_enhancer.entity:
     class: Drupal\Core\Entity\Enhancer\EntityRouteEnhancer
     tags:
@@ -1094,7 +1094,8 @@ services:
     arguments: ['@current_user', '@session_manager']
   current_user:
     class: Drupal\Core\Session\AccountProxy
-    arguments: ['@authentication', '@request_stack']
+    tags:
+      - { name: persist }
   session_configuration:
     class: Drupal\Core\Session\SessionConfiguration
     arguments: ['%session.storage.options%']
@@ -1111,7 +1112,7 @@ services:
     alias: session_handler.storage
   session_handler.storage:
     class: Drupal\Core\Session\SessionHandler
-    arguments: ['@request_stack', '@database']
+    arguments: ['@request_stack', '@database', '@current_user']
     tags:
       - { name: backend_overridable }
   session_handler.write_check:
diff --git a/core/lib/Drupal/Core/Authentication/AuthenticationManager.php b/core/lib/Drupal/Core/Authentication/AuthenticationManager.php
index c4c1df4..822f020 100644
--- a/core/lib/Drupal/Core/Authentication/AuthenticationManager.php
+++ b/core/lib/Drupal/Core/Authentication/AuthenticationManager.php
@@ -171,18 +171,9 @@ protected function filterProviders(array $providers, Request $request) {
     $allowed_providers = array();
     if ($route && $route->hasOption('_auth')) {
       $allowed_providers = $route->getOption('_auth');
+      $providers = array_intersect_key($providers, array_flip($allowed_providers));
     }
-    elseif ($default_provider = $this->defaultProviderId()) {
-      // @todo Mirrors the defective behavior of AuthenticationEnhancer and
-      // restricts the list of allowed providers to the default provider if no
-      // _auth was specified on the current route.
-      //
-      // This restriction will be removed by https://www.drupal.org/node/2286971
-      // See also https://www.drupal.org/node/2283637
-      $allowed_providers = array($default_provider);
-    }
-
-    return array_intersect_key($providers, array_flip($allowed_providers));
+    return $providers;
   }
 
   /**
diff --git a/core/lib/Drupal/Core/Authentication/Provider/Cookie.php b/core/lib/Drupal/Core/Authentication/Provider/Cookie.php
index e36275f..517a48c 100644
--- a/core/lib/Drupal/Core/Authentication/Provider/Cookie.php
+++ b/core/lib/Drupal/Core/Authentication/Provider/Cookie.php
@@ -7,8 +7,12 @@
 
 namespace Drupal\Core\Authentication\Provider;
 
+use Drupal\Component\Utility\Crypt;
 use Drupal\Core\Authentication\AuthenticationProviderInterface;
-use Drupal\Core\Session\SessionManagerInterface;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AnonymousUserSession;
+use Drupal\Core\Session\UserSession;
+use Drupal\Core\Site\Settings;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
 
@@ -18,6 +22,23 @@
 class Cookie implements AuthenticationProviderInterface {
 
   /**
+   * The database connection.
+   *
+   * @var \Drupal\Core\Database\Connection
+   */
+  protected $connection;
+
+  /**
+   * Constructs a new Cookie authentication provider.
+   *
+   * @param \Drupal\Core\Database\Connection $connection
+   *   The database connection.
+   */
+  public function __construct(Connection $connection) {
+    $this->connection = $connection;
+  }
+
+  /**
    * {@inheritdoc}
    */
   public function applies(Request $request) {
@@ -28,13 +49,49 @@ public function applies(Request $request) {
    * {@inheritdoc}
    */
   public function authenticate(Request $request) {
-    // Global $user is deprecated, but the session system is still based on it.
-    global $user;
+    $session = $request->getSession();
+    if ($session->start()) {
+      // Handle the case of first time visitors and clients that don't store
+      // cookies (eg. web crawlers).
+      $cookies = $request->cookies;
+      if (!$cookies->has($session->getName())) {
+        return new AnonymousUserSession();
+      }
 
-    if ($request->getSession()->start()) {
+      $values = $this->connection->query("SELECT u.*, s.* FROM {users_field_data} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE u.default_langcode = 1 AND s.sid = :sid", array(
+        ':sid' => Crypt::hashBase64($session->getId()),
+      ))->fetchAssoc();
+
+      // We found the client's session record and they are an authenticated,
+      // active user.
+      if ($values && $values['uid'] > 0 && $values['status'] == 1) {
+        // Add roles element to $user.
+        $rids = $this->connection->query("SELECT ur.roles_target_id as rid FROM {user__roles} ur WHERE ur.entity_id = :uid", array(
+          ':uid' => $values['uid'],
+        ))->fetchCol();
+        $values['roles'] = array_merge(array(DRUPAL_AUTHENTICATED_RID), $rids);
+        $user = new UserSession($values);
+      }
+      elseif ($values) {
+        // The user is anonymous or blocked. Only preserve two fields from the
+        // {sessions} table.
+        $user = new UserSession(array(
+          'session' => $values['session'],
+          'access' => $values['access'],
+        ));
+      }
+      else {
+        // The session has expired.
+        $user = new AnonymousUserSession();
+      }
+      // Likewise, do not update access time more than once per 180 seconds.
+      if ($user->isAuthenticated() && REQUEST_TIME - $user->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
+        /** @var \Drupal\user\UserStorageInterface $storage */
+        $storage = \Drupal::entityManager()->getStorage('user');
+        $storage->updateLastAccessTimestamp($user, REQUEST_TIME);
+      }
       return $user;
     }
-
     return NULL;
   }
 
diff --git a/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php b/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php
index 80f7796..07fa66b 100644
--- a/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php
+++ b/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php
@@ -63,11 +63,6 @@ public function onException(GetResponseForExceptionEvent $event) {
 
   /**
    * {@inheritdoc}
-   *
-   * The priority for request must be higher than the highest event subscriber
-   * accessing the current user.
-   * The priority for the response must be as low as possible allowing e.g the
-   * Cookie provider to send all relevant session data to the user.
    */
   public static function getSubscribedEvents() {
     $events[KernelEvents::RESPONSE][] = ['onRespond', 0];
diff --git a/core/lib/Drupal/Core/Routing/AccessAwareRouter.php b/core/lib/Drupal/Core/Routing/AccessAwareRouter.php
index 93a31c3..e05a3e4 100644
--- a/core/lib/Drupal/Core/Routing/AccessAwareRouter.php
+++ b/core/lib/Drupal/Core/Routing/AccessAwareRouter.php
@@ -8,7 +8,8 @@
 namespace Drupal\Core\Routing;
 
 use Drupal\Core\Access\AccessManagerInterface;
-use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\Authentication\AuthenticationProviderInterface;
+use Drupal\Core\Session\AccountProxyInterface;
 use Symfony\Cmf\Component\Routing\ChainRouter;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@@ -34,11 +35,18 @@ class AccessAwareRouter implements AccessAwareRouterInterface {
   protected $accessManager;
 
   /**
-   * The account to use in access checks.
+   * Authentication provider.
    *
-   * @var \Drupal\Core\Session\AccountInterface;
+   * @var \Drupal\Core\Authentication\AuthenticationProviderInterface
    */
-  protected $account;
+  protected $authenticationProvider;
+
+  /**
+   * The account proxy to authenticate and to use in access checks.
+   *
+   * @var \Drupal\Core\Session\AccountProxyInterface;
+   */
+  protected $accountProxy;
 
   /**
    * Constructs a router for Drupal with access check and upcasting.
@@ -47,13 +55,16 @@ class AccessAwareRouter implements AccessAwareRouterInterface {
    *   The chain router doing the actual routing.
    * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
    *   The access manager.
-   * @param \Drupal\Core\Session\AccountInterface $account
-   *   The account to use in access checks.
+   * @param \Drupal\Core\Authentication\AuthenticationProviderInterface $authentication_provider
+   *   The authentication provider.
+   * @param \Drupal\Core\Session\AccountProxyInterface $account_proxy
+   *   The account proxy to authenticate and to use in access checks.
    */
-  public function __construct(ChainRouter $chain_router, AccessManagerInterface $access_manager, AccountInterface $account) {
+  public function __construct(ChainRouter $chain_router, AccessManagerInterface $access_manager, AuthenticationProviderInterface $authentication_provider, AccountProxyInterface $account_proxy) {
     $this->chainRouter = $chain_router;
     $this->accessManager = $access_manager;
-    $this->account = $account;
+    $this->authenticationProvider = $authentication_provider;
+    $this->accountProxy = $account_proxy;
   }
 
   /**
@@ -86,12 +97,22 @@ public function getContext() {
    *   Thrown when access checking failed.
    */
   public function matchRequest(Request $request) {
-    $parameters = $this->chainRouter->matchRequest($request);
-    $request->attributes->add($parameters);
-    // Trigger a session start and authentication by accessing any property of
-    // the current user.
-    // @todo This will be removed in https://www.drupal.org/node/2229145.
-    $this->account->id();
+    try {
+      $parameters = $this->chainRouter->matchRequest($request);
+      $request->attributes->add($parameters);
+    }
+    catch (\Exception $e) {
+      try {
+//        $this->accountProxy->setAccount($this->authenticationProvider->authenticate($request));
+      }
+      catch (\Exception $e) {
+        // Ignore exception thrown while trying to authenticate inside the
+        // enclosing catch clause.
+      }
+
+      throw $e;
+    }
+
     $this->checkAccess($request);
     // We can not return $parameters because the access check can change the
     // request attributes.
@@ -105,7 +126,7 @@ public function matchRequest(Request $request) {
    *   The request to access check.
    */
   protected function checkAccess(Request $request) {
-    if (!$this->accessManager->checkRequest($request, $this->account)) {
+    if (!$this->accessManager->checkRequest($request, $this->accountProxy)) {
       throw new AccessDeniedHttpException();
     }
   }
diff --git a/core/lib/Drupal/Core/Routing/Enhancer/AuthenticationEnhancer.php b/core/lib/Drupal/Core/Routing/Enhancer/AuthenticationEnhancer.php
index e032ab1..6327696 100644
--- a/core/lib/Drupal/Core/Routing/Enhancer/AuthenticationEnhancer.php
+++ b/core/lib/Drupal/Core/Routing/Enhancer/AuthenticationEnhancer.php
@@ -7,72 +7,73 @@
 
 namespace Drupal\Core\Routing\Enhancer;
 
-use Drupal\Core\Authentication\AuthenticationManagerInterface;
+use Drupal\Core\Authentication\AuthenticationProviderInterface;
 use Drupal\Core\Session\AccountProxyInterface;
-use Drupal\Core\Session\AnonymousUserSession;
 use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\RequestStack;
 use Symfony\Component\Routing\Route;
-use Symfony\Cmf\Component\Routing\RouteObjectInterface;
 
 /**
- * Authentication cleanup for incoming routes.
+ * Authenticates the incomming request.
  *
- * The authentication system happens before routing, so all authentication
- * providers will attempt to authorize a user. However, not all routes allow
- * all authentication mechanisms. Instead, we check if the used provider is
- * valid for the matched route and if not, force the user to anonymous.
+ * Routes may restrict the list of available authentication methods via their
+ * _auth option. Hence, user authentication needs to take place after a route
+ * has been selected. On the other hand some route enhancers need the current
+ * user to be present. E.g. when upcasting, entities are expected to be loaded
+ * in the correct language. This is the reason why authentication currently is
+ * performed from within a route enhancer.
  */
 class AuthenticationEnhancer implements RouteEnhancerInterface {
 
   /**
-   * The authentication manager.
+   * Authentication provider.
    *
-   * @var \Drupal\Core\Authentication\AuthenticationManager
+   * @var \Drupal\Core\Authentication\AuthenticationProviderInterface
    */
-  protected $manager;
+  protected $authenticationProvider;
 
   /**
-   * The current user service.
+   * The account proxy to authenticate.
    *
    * @var \Drupal\Core\Session\AccountProxyInterface
    */
-  protected $currentUser;
+  protected $accountProxy;
+
+  /**
+   * The request stack.
+   *
+   * @var \Symfony\Component\HttpFoundation\RequestStack
+   */
+  protected $requestStack;
 
   /**
    * Constructs a AuthenticationEnhancer object.
    *
-   * @param \Drupal\Core\Authentication\AuthenticationManagerInterface $manager
-   *   The authentication manager.
-   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
-   *   The current user service.
+   * @param \Drupal\Core\Authentication\AuthenticationProviderInterface $authentication_provider
+   *   The authentication provider.
+   * @param \Drupal\Core\Session\AccountProxyInterface $account_proxy
+   *   The account proxy to authenticate.
+   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
+   *   The request stack.
    */
-  function __construct(AuthenticationManagerInterface $manager, AccountProxyInterface $current_user) {
-    $this->manager = $manager;
-    $this->currentUser = $current_user;
+  public function __construct(AuthenticationProviderInterface $authentication_provider, AccountProxyInterface $account_proxy, RequestStack $request_stack) {
+    $this->authenticationProvider = $authentication_provider;
+    $this->accountProxy = $account_proxy;
+    $this->requestStack = $request_stack;
   }
 
   /**
    * {@inheritdoc}
    */
   public function enhance(array $defaults, Request $request) {
-    $auth_provider_triggered = $request->attributes->get('_authentication_provider');
-    if (!empty($auth_provider_triggered)) {
-      $route = isset($defaults[RouteObjectInterface::ROUTE_OBJECT]) ? $defaults[RouteObjectInterface::ROUTE_OBJECT] : NULL;
-
-      $auth_providers = ($route && $route->getOption('_auth')) ? $route->getOption('_auth') : array($this->manager->defaultProviderId());
-      // If the request was authenticated with a non-permitted provider,
-      // force the user back to anonymous.
-      if (!in_array($auth_provider_triggered, $auth_providers)) {
-        $anonymous_user = new AnonymousUserSession();
-
-        $this->currentUser->setAccount($anonymous_user);
-
-        // The global $user object is included for backward compatibility only
-        // and should be considered deprecated.
-        // @todo Remove this line once global $user is no longer used.
-        $GLOBALS['user'] = $anonymous_user;
-      }
+    // Authenticate the user if the request currently being routed is the
+    // incomming master request.
+    if ($request === $this->requestStack->getMasterRequest()) {
+      // Apply the defaults to current request for authentication providers.
+      $request->attributes->add($defaults);
+      $this->accountProxy->setAccount($this->authenticationProvider->authenticate($request));
     }
+
     return $defaults;
   }
 
diff --git a/core/lib/Drupal/Core/Session/AccountProxy.php b/core/lib/Drupal/Core/Session/AccountProxy.php
index f9d0d35..ca671a4 100644
--- a/core/lib/Drupal/Core/Session/AccountProxy.php
+++ b/core/lib/Drupal/Core/Session/AccountProxy.php
@@ -7,9 +7,6 @@
 
 namespace Drupal\Core\Session;
 
-use Drupal\Core\Authentication\AuthenticationManagerInterface;
-use Symfony\Component\HttpFoundation\RequestStack;
-
 /**
  * A proxied implementation of AccountInterface.
  *
@@ -24,20 +21,6 @@
 class AccountProxy implements AccountProxyInterface {
 
   /**
-   * The current request.
-   *
-   * @var \Symfony\Component\HttpFoundation\RequestStack
-   */
-  protected $requestStack;
-
-  /**
-   * The authentication manager.
-   *
-   * @var \Drupal\Core\Authentication\AuthenticationManagerInterface
-   */
-  protected $authenticationManager;
-
-  /**
    * The instantiated account.
    *
    * @var \Drupal\Core\Session\AccountInterface
@@ -46,15 +29,9 @@ class AccountProxy implements AccountProxyInterface {
 
   /**
    * Constructs a new AccountProxy.
-   *
-   * @param \Drupal\Core\Authentication\AuthenticationManagerInterface $authentication_manager
-   *   The authentication manager.
-   * @param \Symfony\Component\HttpFoundation\Request $request
-   *   The request object used for authenticating.
    */
-  public function __construct(AuthenticationManagerInterface $authentication_manager, RequestStack $requestStack) {
-    $this->authenticationManager = $authentication_manager;
-    $this->requestStack = $requestStack;
+  public function __construct() {
+    $this->account = new AnonymousUserSession();
   }
 
   /**
@@ -73,11 +50,6 @@ public function setAccount(AccountInterface $account) {
    * {@inheritdoc}
    */
   public function getAccount() {
-    if (!isset($this->account)) {
-      // Use the master request to prevent subrequests authenticating to a
-      // different user.
-      $this->setAccount($this->authenticationManager->authenticate($this->requestStack->getMasterRequest()));
-    }
     return $this->account;
   }
 
@@ -187,4 +159,3 @@ public function getLastAccessedTime() {
   }
 
 }
-
diff --git a/core/lib/Drupal/Core/Session/SessionHandler.php b/core/lib/Drupal/Core/Session/SessionHandler.php
index f46794f..c87a496 100644
--- a/core/lib/Drupal/Core/Session/SessionHandler.php
+++ b/core/lib/Drupal/Core/Session/SessionHandler.php
@@ -34,6 +34,13 @@ class SessionHandler extends AbstractProxy implements \SessionHandlerInterface {
   protected $connection;
 
   /**
+   * The current user account.
+   *
+   * @var \Drupal\Core\Session\AccountInterface
+   */
+  protected $currentUser;
+
+  /**
    * An associative array of obsolete sessions with session id as key, and db-key as value.
    *
    * @var array
@@ -47,10 +54,13 @@ class SessionHandler extends AbstractProxy implements \SessionHandlerInterface {
    *   The request stack.
    * @param \Drupal\Core\Database\Connection $connection
    *   The database connection.
+   * @param \Drupal\Core\Session\AccountInterface $current_user
+   *   The current user account.
    */
-  public function __construct(RequestStack $request_stack, Connection $connection) {
+  public function __construct(RequestStack $request_stack, Connection $connection, AccountInterface $current_user) {
     $this->requestStack = $request_stack;
     $this->connection = $connection;
+    $this->currentUser = $current_user;
   }
 
   /**
@@ -64,57 +74,30 @@ public function open($save_path, $name) {
    * {@inheritdoc}
    */
   public function read($sid) {
-    global $user;
-
-    // Handle the case of first time visitors and clients that don't store
-    // cookies (eg. web crawlers).
-    $cookies = $this->requestStack->getCurrentRequest()->cookies;
-    if (empty($sid) || !$cookies->has($this->getName())) {
-      $user = new UserSession();
-      return '';
-    }
+    // Read the session data from the database.
+    $record = $this->connection->select('sessions', 's')
+      ->fields('s')
+      ->condition('sid', Crypt::hashBase64($sid))
+      ->execute()
+      ->fetchAssoc();
 
-    $values = $this->connection->query("SELECT u.*, s.* FROM {users_field_data} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE u.default_langcode = 1 AND s.sid = :sid", array(
-      ':sid' => Crypt::hashBase64($sid),
-    ))->fetchAssoc();
-
-    // We found the client's session record and they are an authenticated,
-    // active user.
-    if ($values && $values['uid'] > 0 && $values['status'] == 1) {
-      // Add roles element to $user.
-      $rids = $this->connection->query("SELECT ur.roles_target_id as rid FROM {user__roles} ur WHERE ur.entity_id = :uid", array(
-        ':uid' => $values['uid'],
-      ))->fetchCol();
-      $values['roles'] = array_merge(array(DRUPAL_AUTHENTICATED_RID), $rids);
-      $user = new UserSession($values);
-    }
-    elseif ($values) {
-      // The user is anonymous or blocked. Only preserve two fields from the
-      // {sessions} table.
-      $user = new UserSession(array(
-        'session' => $values['session'],
-        'access' => $values['access'],
-      ));
+    if (isset($record['session'])) {
+      return $record['session'];
     }
     else {
-      // The session has expired.
-      $user = new UserSession();
+      return '';
     }
-
-    return $user->session;
   }
 
   /**
    * {@inheritdoc}
    */
   public function write($sid, $value) {
-    global $user;
-
     // The exception handler is not active at this point, so we need to do it
     // manually.
     try {
       $fields = array(
-        'uid' => $user->id(),
+        'uid' => $this->currentUser->id(),
         'hostname' => $this->requestStack->getCurrentRequest()->getClientIP(),
         'session' => $value,
         'timestamp' => REQUEST_TIME,
@@ -123,13 +106,6 @@ public function write($sid, $value) {
         ->keys(array('sid' => Crypt::hashBase64($sid)))
         ->fields($fields)
         ->execute();
-
-      // Likewise, do not update access time more than once per 180 seconds.
-      if ($user->isAuthenticated() && REQUEST_TIME - $user->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
-        /** @var \Drupal\user\UserStorageInterface $storage */
-        $storage = \Drupal::entityManager()->getStorage('user');
-        $storage->updateLastAccessTimestamp($user, REQUEST_TIME);
-      }
       return TRUE;
     }
     catch (\Exception $exception) {
@@ -165,8 +141,12 @@ public function destroy($sid) {
     // Reset $_SESSION and $user to prevent a new session from being started
     // in \Drupal\Core\Session\SessionManager::save().
     $_SESSION = array();
+
+    // @todo: Manipulating the current user is not the business of the session
+    // handler. This should be moved to the authentication mananger.
     $user = new AnonymousUserSession();
 
+    // @todo: cookie management should be moved to Cookie auth manager.
     // Unset the session cookies.
     $this->deleteCookie($this->getName());
 
@@ -193,6 +173,8 @@ public function gc($lifetime) {
    *
    * @param string $name
    *   Name of session cookie to delete.
+   *
+   * @todo: cookie management should be moved to Cookie auth manager.
    */
   protected function deleteCookie($name) {
     $cookies = $this->requestStack->getCurrentRequest()->cookies;
diff --git a/core/lib/Drupal/Core/Session/SessionManager.php b/core/lib/Drupal/Core/Session/SessionManager.php
index 8249805..43fffa9 100644
--- a/core/lib/Drupal/Core/Session/SessionManager.php
+++ b/core/lib/Drupal/Core/Session/SessionManager.php
@@ -181,14 +181,14 @@ protected function startNow() {
    * {@inheritdoc}
    */
   public function save() {
-    global $user;
+    $user = \Drupal::currentUser();
 
     if ($this->isCli()) {
       // We don't have anything to do if we are not allowed to save the session.
       return;
     }
 
-    if ($user->isAnonymous() && $this->isSessionObsolete()) {
+    if (!$user || ($user->isAnonymous() && $this->isSessionObsolete())) {
       // There is no session data to store, destroy the session if it was
       // previously started.
       if ($this->getSaveHandler()->isActive()) {
diff --git a/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php b/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php
index de41c44..50c88db 100644
--- a/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php
+++ b/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php
@@ -12,11 +12,14 @@
 use Drupal\Core\Config\ConfigFactoryInterface;
 use Drupal\Core\Entity\EntityManagerInterface;
 use Drupal\Core\Flood\FloodInterface;
+use Drupal\Core\Routing\RouteMatch;
 use Drupal\user\UserAuthInterface;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
 use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
+use Symfony\Component\Routing\Route;
+
 
 /**
  * HTTP Basic authentication provider.
@@ -74,9 +77,11 @@ public function __construct(ConfigFactoryInterface $config_factory, UserAuthInte
    * {@inheritdoc}
    */
   public function applies(Request $request) {
-    $username = $request->headers->get('PHP_AUTH_USER');
-    $password = $request->headers->get('PHP_AUTH_PW');
-    return isset($username) && isset($password);
+    if ($this->hasCredentials($request)) {
+      // Only allow basic auth when it was specified explicitely on the route.
+      $route = RouteMatch::createFromRequest($request)->getRouteObject();
+      return isset($route) && $this->appliesToRoute($route);
+    }
   }
 
   /**
@@ -138,8 +143,10 @@ public function cleanup(Request $request) {}
    */
   public function handleException(GetResponseForExceptionEvent $event) {
     $exception = $event->getException();
-    if ($GLOBALS['user']->isAnonymous() && $exception instanceof AccessDeniedHttpException) {
-      if (!$this->applies($event->getRequest())) {
+    $request = $event->getRequest();
+    if ($GLOBALS['user']->isAnonymous() && $exception instanceof AccessDeniedHttpException && !$this->hasCredentials($request)) {
+      $route = RouteMatch::createFromRequest($request)->getRouteObject();
+      if (isset($route) && $this->appliesToRoute($route)) {
         $site_name = $this->configFactory->get('system.site')->get('name');
         global $base_url;
         $challenge = String::format('Basic realm="@realm"', array(
@@ -152,4 +159,32 @@ public function handleException(GetResponseForExceptionEvent $event) {
     return FALSE;
   }
 
+  /**
+   * Returns whether basic auth is enabled on a route.
+   *
+   * @param \Symfony\Component\Routing\Route $route
+   *   The route to be checked.
+   *
+   * @return bool
+   *   TRUE if basic auth is enabled, FALSE otherwise.
+   */
+  protected function appliesToRoute(Route $route) {
+    return $route->hasOption('_auth') && in_array('basic_auth', $route->getOption('_auth'));
+  }
+
+  /**
+   * Returns whether basic auth credentials are on the request.
+   *
+   * @param \Symfony\Component\HttpFoundation\Request $request
+   *   The request to be checked.
+   *
+   * @return bool
+   *   TRUE if basic auth credentials are on the request, FALSE otherwise.
+   */
+  protected function hasCredentials(Request $request) {
+    $username = $request->headers->get('PHP_AUTH_USER');
+    $password = $request->headers->get('PHP_AUTH_PW');
+    return isset($username) && isset($password);
+  }
+
 }
diff --git a/core/modules/user/user.module b/core/modules/user/user.module
index 5d39ce3..aa9e329 100644
--- a/core/modules/user/user.module
+++ b/core/modules/user/user.module
@@ -595,9 +595,6 @@ function user_menu_breadcrumb_alter(&$active_trail, $item) {
  * @see hook_user_login()
  */
 function user_login_finalize(UserInterface $account) {
-  global $user;
-  $user = $account;
-  \Drupal::logger('user')->notice('Session opened for %name.', array('%name' => $account->getUsername()));
   // Update the user table timestamp noting user has logged in.
   // This is also used to invalidate one-time login links.
   $account->setLastLoginTime(REQUEST_TIME);
@@ -609,7 +606,9 @@ function user_login_finalize(UserInterface $account) {
   // This is called before hook_user_login() in case one of those functions
   // fails or incorrectly does a redirect which would leave the old session
   // in place.
+  \Drupal::currentUser()->setAccount($account);
   \Drupal::service('session')->migrate();
+  \Drupal::logger('user')->notice('Session opened for %name.', array('%name' => $account->getUsername()));
 
   \Drupal::moduleHandler()->invokeAll('user_login', array($account));
 }
diff --git a/core/modules/user/user.services.yml b/core/modules/user/user.services.yml
index 8a4f4f0..f642395 100644
--- a/core/modules/user/user.services.yml
+++ b/core/modules/user/user.services.yml
@@ -17,6 +17,7 @@ services:
       - { name: access_check, applies_to: _user_is_logged_in }
   authentication.cookie:
     class: Drupal\Core\Authentication\Provider\Cookie
+    arguments: ['@database']
     tags:
       - { name: authentication_provider, priority: 0 }
   cache_context.user:
diff --git a/core/tests/Drupal/Tests/Core/Routing/AccessAwareRouterTest.php b/core/tests/Drupal/Tests/Core/Routing/AccessAwareRouterTest.php
index 3e8676f..c4f1284 100644
--- a/core/tests/Drupal/Tests/Core/Routing/AccessAwareRouterTest.php
+++ b/core/tests/Drupal/Tests/Core/Routing/AccessAwareRouterTest.php
@@ -35,9 +35,16 @@ class AccessAwareRouterTest extends UnitTestCase {
   protected $accessManager;
 
   /**
-   * @var \Drupal\Core\Session\AccountInterface||\PHPUnit_Framework_MockObject_MockObject
+   * Authentication provider.
+   *
+   * @var \Drupal\Core\Authentication\AuthenticationProviderInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $authenticationProvider;
+
+  /**
+   * @var \Drupal\Core\Session\AccountProxyInterface|\PHPUnit_Framework_MockObject_MockObject
    */
-  protected $currentUser;
+  protected $accountProxy;
 
   /**
    * @var \Drupal\Core\Routing\AccessAwareRouter
@@ -51,7 +58,8 @@ public function setUp() {
     parent::setUp();
     $this->route = new Route('test');
     $this->accessManager = $this->getMock('Drupal\Core\Access\AccessManagerInterface');
-    $this->currentUser = $this->getMock('Drupal\Core\Session\AccountInterface');
+    $this->authenticationProvider = $this->getMock('Drupal\Core\Authentication\AuthenticationProviderInterface');
+    $this->accountProxy = $this->getMock('Drupal\Core\Session\AccountProxyInterface');
   }
 
   /**
@@ -64,7 +72,10 @@ protected function setupRouter() {
     $this->chainRouter->expects($this->once())
       ->method('matchRequest')
       ->will($this->returnValue(array(RouteObjectInterface::ROUTE_OBJECT => $this->route)));
-    $this->router = new AccessAwareRouter($this->chainRouter, $this->accessManager, $this->currentUser);
+    $this->authenticationProvider->expects($this->once())
+      ->method('authenticate')
+      ->will($this->returnValue($this->getMock('Drupal\Core\Session\AccountInterface')));
+    $this->router = new AccessAwareRouter($this->chainRouter, $this->accessManager, $this->authenticationProvider, $this->accountProxy);
   }
 
   /**
@@ -113,7 +124,7 @@ public function testCall() {
       ->method('add')
       ->with($mock_router)
       ->willReturnSelf();
-    $this->router = new AccessAwareRouter($this->chainRouter, $this->accessManager, $this->currentUser);
+    $this->router = new AccessAwareRouter($this->chainRouter, $this->accessManager, $this->authenticationProvider, $this->accountProxy);
 
     $this->router->add($mock_router);
   }
