diff --git a/core/authorize.php b/core/authorize.php
index dbab02f..6896e79 100644
--- a/core/authorize.php
+++ b/core/authorize.php
@@ -47,11 +47,16 @@
  * The killswitch in settings.php overrides all else, otherwise, the user must
  * have access to the 'administer software updates' permission.
  *
+ * @param \Symfony\Component\HttpFoundation\Request $request
+ *  The incoming request.
+ *
  * @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 +84,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 a077397..8e19754 100644
--- a/core/core.services.yml
+++ b/core/core.services.yml
@@ -720,11 +720,6 @@ services:
     tags:
       - { name: route_enhancer }
       - { name: event_subscriber }
-  route_enhancer.authentication:
-    class: Drupal\Core\Routing\Enhancer\AuthenticationEnhancer
-    tags:
-      - { name: route_enhancer, priority: 1000 }
-    arguments: ['@authentication', '@current_user']
   route_enhancer.entity:
     class: Drupal\Core\Entity\Enhancer\EntityRouteEnhancer
     tags:
@@ -1092,15 +1087,16 @@ services:
       - { name: service_collector, tag: authentication_provider, call: addProvider }
   authentication_subscriber:
     class: Drupal\Core\EventSubscriber\AuthenticationSubscriber
+    arguments: ['@authentication', '@current_user']
     tags:
       - { name: event_subscriber }
-    arguments: ['@authentication']
   account_switcher:
     class: Drupal\Core\Session\AccountSwitcher
     arguments: ['@current_user', '@session_handler.write_safe']
   current_user:
     class: Drupal\Core\Session\AccountProxy
-    arguments: ['@authentication', '@request_stack']
+    calls:
+      - [setContainer, ['@service_container']]
   session_configuration:
     class: Drupal\Core\Session\SessionConfiguration
     arguments: ['%session.storage.options%']
diff --git a/core/lib/Drupal/Core/Authentication/AuthenticationManager.php b/core/lib/Drupal/Core/Authentication/AuthenticationManager.php
index c4c1df4..4cfda90 100644
--- a/core/lib/Drupal/Core/Authentication/AuthenticationManager.php
+++ b/core/lib/Drupal/Core/Authentication/AuthenticationManager.php
@@ -90,7 +90,7 @@ public function authenticate(Request $request) {
     $account = NULL;
 
     // Iterate the allowed providers.
-    foreach ($this->filterProviders($this->getSortedProviders(), $request) as $provider_id => $provider) {
+    foreach ($this->getSortedProviders() as $provider_id => $provider) {
       if ($provider->applies($request)) {
         // Try to authenticate with this provider, skipping all others.
         $account = $provider->authenticate($request);
@@ -156,36 +156,6 @@ public function getSortedProviders() {
   }
 
   /**
-   * Filters a list of providers and only return those allowed on the request.
-   *
-   * @param \Drupal\Core\Authentication\AuthenticationProviderInterface[] $providers
-   *   An array of authentication provider objects.
-   * @param Request $request
-   *   The request object.
-   *
-   * @return \Drupal\Core\Authentication\AuthenticationProviderInterface[]
-   *   The filtered array authentication provider objects.
-   */
-  protected function filterProviders(array $providers, Request $request) {
-    $route = RouteMatch::createFromRequest($request)->getRouteObject();
-    $allowed_providers = array();
-    if ($route && $route->hasOption('_auth')) {
-      $allowed_providers = $route->getOption('_auth');
-    }
-    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));
-  }
-
-  /**
    * Cleans up the authentication.
    *
    * Allow the triggered provider to clean up before the response is sent, e.g.
@@ -207,7 +177,7 @@ public function cleanup(Request $request) {
    * {@inheritdoc}
    */
   public function handleException(GetResponseForExceptionEvent $event) {
-    foreach ($this->filterProviders($this->getSortedProviders(), $event->getRequest()) as $provider) {
+    foreach ($this->getSortedProviders() as $provider) {
       if ($provider->handleException($event) === TRUE) {
         break;
       }
diff --git a/core/lib/Drupal/Core/Authentication/Provider/Cookie.php b/core/lib/Drupal/Core/Authentication/Provider/Cookie.php
index e36275f..d7c8636 100644
--- a/core/lib/Drupal/Core/Authentication/Provider/Cookie.php
+++ b/core/lib/Drupal/Core/Authentication/Provider/Cookie.php
@@ -8,6 +8,7 @@
 namespace Drupal\Core\Authentication\Provider;
 
 use Drupal\Core\Authentication\AuthenticationProviderInterface;
+use Drupal\Core\Session\SessionConfigurationInterface;
 use Drupal\Core\Session\SessionManagerInterface;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
@@ -18,10 +19,27 @@
 class Cookie implements AuthenticationProviderInterface {
 
   /**
+   * The session configuration.
+   *
+   * @var \Drupal\Core\Session\SessionConfigurationInterface
+   */
+  protected $sessionConfiguration;
+
+  /**
+   * Constructs a new cookie authentication provider.
+   *
+   * @param \Drupal\Core\Session\SessionConfigurationInterface $session_configuration
+   *   The session configuration.
+   */
+  public function __construct(SessionConfigurationInterface $session_configuration) {
+    $this->sessionConfiguration = $session_configuration;
+  }
+
+  /**
    * {@inheritdoc}
    */
   public function applies(Request $request) {
-    return $request->hasSession();
+    return $request->hasSession() && $this->sessionConfiguration->hasSession($request);
   }
 
   /**
diff --git a/core/lib/Drupal/Core/DrupalKernel.php b/core/lib/Drupal/Core/DrupalKernel.php
index 0e679fd..ed62270 100644
--- a/core/lib/Drupal/Core/DrupalKernel.php
+++ b/core/lib/Drupal/Core/DrupalKernel.php
@@ -685,6 +685,11 @@ protected function initializeContainer($rebuild = FALSE) {
     $this->containerNeedsDumping = FALSE;
     $session_manager_started = FALSE;
     if (isset($this->container)) {
+      // Save the id of the currently logged in user.
+      if ($this->container->initialized('current_user')) {
+        $current_user_id = $this->container->get('current_user')->id();
+      }
+
       // If there is a session manager, close and save the session.
       if ($this->container->initialized('session_manager')) {
         $session_manager = $this->container->get('session_manager');
@@ -731,6 +736,11 @@ protected function initializeContainer($rebuild = FALSE) {
         }
       }
     }
+
+    if (!empty($current_user_id)) {
+      $this->container->get('current_user')->setInitialAccountId($current_user_id);
+    }
+
     \Drupal::setContainer($this->container);
 
     // If needs dumping flag was set, dump the container.
diff --git a/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php b/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php
index 80f7796..4f5f7bf 100644
--- a/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php
+++ b/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php
@@ -8,8 +8,10 @@
 namespace Drupal\Core\EventSubscriber;
 
 use Drupal\Core\Authentication\AuthenticationProviderInterface;
+use Drupal\Core\Session\AccountProxyInterface;
 use Symfony\Component\HttpKernel\HttpKernelInterface;
 use Symfony\Component\HttpKernel\KernelEvents;
+use Symfony\Component\HttpKernel\Event\GetResponseEvent;
 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
@@ -24,18 +26,41 @@ class AuthenticationSubscriber implements EventSubscriberInterface {
   /**
    * Authentication provider.
    *
-   * @var AuthenticationProviderInterface
+   * @var \Drupal\Core\Authentication\AuthenticationProviderInterface
    */
   protected $authenticationProvider;
 
   /**
+   * Account proxy.
+   *
+   * @var \Drupal\Core\Session\AccountProxyInterface
+   */
+  protected $accountProxy;
+
+  /**
    * Keep authentication manager as private variable.
    *
-   * @param AuthenticationProviderInterface $authentication_manager
+   * @param \Drupal\Core\Authentication\AuthenticationProviderInterface $authentication_manager
    *   The authentication manager.
+   * @param \Drupal\Core\Session\AccountProxyInterface $account_proxy
+   *   Account proxy.
    */
-  public function __construct(AuthenticationProviderInterface $authentication_provider) {
+  public function __construct(AuthenticationProviderInterface $authentication_provider, AccountProxyInterface $account_proxy) {
     $this->authenticationProvider = $authentication_provider;
+    $this->accountProxy = $account_proxy;
+  }
+
+  /**
+   * Authenticates user on request.
+   *
+   * @see \Drupal\Core\Authentication\AuthenticationProviderInterface::authenticate()
+   */
+  public function onKernelRequestAuthenticate(GetResponseEvent $event) {
+    if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) {
+      $request = $event->getRequest();
+      $account = $this->authenticationProvider->authenticate($request);
+      $this->accountProxy->setAccount($account);
+    }
   }
 
   /**
@@ -70,6 +95,9 @@ public function onException(GetResponseForExceptionEvent $event) {
    * Cookie provider to send all relevant session data to the user.
    */
   public static function getSubscribedEvents() {
+    // Priority must be higher than LanguageRequestSubscriber as LanguageManager
+    // access current user in case language module enabled.
+    $events[KernelEvents::REQUEST][] = array('onKernelRequestAuthenticate', 300);
     $events[KernelEvents::RESPONSE][] = ['onRespond', 0];
     $events[KernelEvents::EXCEPTION][] = ['onException', 75];
     return $events;
diff --git a/core/lib/Drupal/Core/Routing/AccessAwareRouter.php b/core/lib/Drupal/Core/Routing/AccessAwareRouter.php
index 93a31c3..1cf937c 100644
--- a/core/lib/Drupal/Core/Routing/AccessAwareRouter.php
+++ b/core/lib/Drupal/Core/Routing/AccessAwareRouter.php
@@ -88,10 +88,6 @@ public function getContext() {
   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();
     $this->checkAccess($request);
     // We can not return $parameters because the access check can change the
     // request attributes.
diff --git a/core/lib/Drupal/Core/Routing/Enhancer/AuthenticationEnhancer.php b/core/lib/Drupal/Core/Routing/Enhancer/AuthenticationEnhancer.php
deleted file mode 100644
index e032ab1..0000000
--- a/core/lib/Drupal/Core/Routing/Enhancer/AuthenticationEnhancer.php
+++ /dev/null
@@ -1,86 +0,0 @@
-<?php
-
-/**
- * @file
- * Contains \Drupal\Core\Routing\Enhancer\AuthenticationEnhancer.
- */
-
-namespace Drupal\Core\Routing\Enhancer;
-
-use Drupal\Core\Authentication\AuthenticationManagerInterface;
-use Drupal\Core\Session\AccountProxyInterface;
-use Drupal\Core\Session\AnonymousUserSession;
-use Symfony\Component\HttpFoundation\Request;
-use Symfony\Component\Routing\Route;
-use Symfony\Cmf\Component\Routing\RouteObjectInterface;
-
-/**
- * Authentication cleanup for incoming routes.
- *
- * 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.
- */
-class AuthenticationEnhancer implements RouteEnhancerInterface {
-
-  /**
-   * The authentication manager.
-   *
-   * @var \Drupal\Core\Authentication\AuthenticationManager
-   */
-  protected $manager;
-
-  /**
-   * The current user service.
-   *
-   * @var \Drupal\Core\Session\AccountProxyInterface
-   */
-  protected $currentUser;
-
-  /**
-   * Constructs a AuthenticationEnhancer object.
-   *
-   * @param \Drupal\Core\Authentication\AuthenticationManagerInterface $manager
-   *   The authentication manager.
-   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
-   *   The current user service.
-   */
-  function __construct(AuthenticationManagerInterface $manager, AccountProxyInterface $current_user) {
-    $this->manager = $manager;
-    $this->currentUser = $current_user;
-  }
-
-  /**
-   * {@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;
-      }
-    }
-    return $defaults;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function applies(Route $route) {
-    return TRUE;
-  }
-
-}
diff --git a/core/lib/Drupal/Core/Session/AccountProxy.php b/core/lib/Drupal/Core/Session/AccountProxy.php
index f9d0d35..6155326 100644
--- a/core/lib/Drupal/Core/Session/AccountProxy.php
+++ b/core/lib/Drupal/Core/Session/AccountProxy.php
@@ -7,8 +7,7 @@
 
 namespace Drupal\Core\Session;
 
-use Drupal\Core\Authentication\AuthenticationManagerInterface;
-use Symfony\Component\HttpFoundation\RequestStack;
+use Symfony\Component\DependencyInjection\ContainerAwareTrait;
 
 /**
  * A proxied implementation of AccountInterface.
@@ -21,21 +20,9 @@
  * allows legacy code to change the current user where the user cannot be
  * directly injected into dependent code.
  */
-class AccountProxy implements AccountProxyInterface {
+class AccountProxy implements AccountProxyInterface, ContainerAwareAccountProxyInterface {
 
-  /**
-   * The current request.
-   *
-   * @var \Symfony\Component\HttpFoundation\RequestStack
-   */
-  protected $requestStack;
-
-  /**
-   * The authentication manager.
-   *
-   * @var \Drupal\Core\Authentication\AuthenticationManagerInterface
-   */
-  protected $authenticationManager;
+  use ContainerAwareTrait;
 
   /**
    * The instantiated account.
@@ -45,17 +32,11 @@ class AccountProxy implements AccountProxyInterface {
   protected $account;
 
   /**
-   * Constructs a new AccountProxy.
+   * Initial account id.
    *
-   * @param \Drupal\Core\Authentication\AuthenticationManagerInterface $authentication_manager
-   *   The authentication manager.
-   * @param \Symfony\Component\HttpFoundation\Request $request
-   *   The request object used for authenticating.
+   * @var int
    */
-  public function __construct(AuthenticationManagerInterface $authentication_manager, RequestStack $requestStack) {
-    $this->authenticationManager = $authentication_manager;
-    $this->requestStack = $requestStack;
-  }
+  protected $initialAccountId;
 
   /**
    * {@inheritdoc}
@@ -74,10 +55,17 @@ public function setAccount(AccountInterface $account) {
    */
   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()));
+      if ($this->initialAccountId) {
+        // After the container is rebuilt, DrupalKernel sets the initial
+        // account to the id of the logged in user. This is necessary such that
+        // it is possible to refresh the user account reference here.
+        $this->account = $this->container->get('entity.manager')->getStorage('user')->load($this->initialAccountId);
+      }
+      else {
+        $this->account = new AnonymousUserSession();
+      }
     }
+
     return $this->account;
   }
 
@@ -186,5 +174,15 @@ public function getLastAccessedTime() {
     return $this->getAccount()->getLastAccessedTime();
   }
 
-}
+  /**
+   * {@inheritdoc}
+   */
+  public function setInitialAccountId($account_id) {
+    if (isset($this->account)) {
+      throw new \LogicException('ContainerAwareAccountProxyInterface::setInitialAccountId() cannot be called after an account was set on the AccountProxy');
+    }
+
+    $this->initialAccountId = $account_id;
+  }
 
+}
diff --git a/core/lib/Drupal/Core/Session/AccountProxyInterface.php b/core/lib/Drupal/Core/Session/AccountProxyInterface.php
index 017bd8b..3de1e2e 100644
--- a/core/lib/Drupal/Core/Session/AccountProxyInterface.php
+++ b/core/lib/Drupal/Core/Session/AccountProxyInterface.php
@@ -38,4 +38,3 @@ public function setAccount(AccountInterface $account);
   public function getAccount();
 
 }
-
diff --git a/core/lib/Drupal/Core/Session/ContainerAwareAccountProxyInterface.php b/core/lib/Drupal/Core/Session/ContainerAwareAccountProxyInterface.php
new file mode 100644
index 0000000..361ab71
--- /dev/null
+++ b/core/lib/Drupal/Core/Session/ContainerAwareAccountProxyInterface.php
@@ -0,0 +1,25 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Session\ContainerAwareAccountProxyInterface.
+ */
+
+namespace Drupal\Core\Session;
+
+use Symfony\Component\DependencyInjection\ContainerAwareInterface;
+
+interface ContainerAwareAccountProxyInterface extends ContainerAwareInterface {
+
+  /**
+   * Sets the id of the initial account.
+   *
+   * Never use this method, its sole purpose is to work around weird effects
+   * during mid-request container rebuilds.
+   *
+   * @param int $account_id
+   *   The id of the initial account.
+   */
+  public function setInitialAccountId($account_id);
+
+}
diff --git a/core/lib/Drupal/Core/StackMiddleware/Session.php b/core/lib/Drupal/Core/StackMiddleware/Session.php
index f92e778..e0ed0e4 100644
--- a/core/lib/Drupal/Core/StackMiddleware/Session.php
+++ b/core/lib/Drupal/Core/StackMiddleware/Session.php
@@ -54,7 +54,9 @@ public function __construct(HttpKernelInterface $http_kernel, $service_name = 's
    */
   public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
     if ($type === self::MASTER_REQUEST && PHP_SAPI !== 'cli') {
-      $request->setSession($this->container->get($this->sessionServiceName));
+      $session = $this->container->get($this->sessionServiceName);
+      $session->start();
+      $request->setSession($session);
     }
 
     $result = $this->httpKernel->handle($request, $type, $catch);
diff --git a/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php b/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php
index de41c44..eb8920c 100644
--- a/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php
+++ b/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php
@@ -12,11 +12,13 @@
 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\HttpKernel\Exception\UnauthorizedHttpException;
+use Symfony\Component\Routing\Route;
 
 /**
  * HTTP Basic authentication provider.
@@ -74,9 +76,7 @@ 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);
+    return $this->hasCredentials($request);
   }
 
   /**
@@ -138,8 +138,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 +154,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/basic_auth/src/Tests/Authentication/BasicAuthTest.php b/core/modules/basic_auth/src/Tests/Authentication/BasicAuthTest.php
index 227f11a..a38b696 100644
--- a/core/modules/basic_auth/src/Tests/Authentication/BasicAuthTest.php
+++ b/core/modules/basic_auth/src/Tests/Authentication/BasicAuthTest.php
@@ -50,11 +50,6 @@ public function testBasicAuth() {
     $this->drupalGet('admin');
     $this->assertResponse('403', 'No authentication prompt for routes not explicitly defining authentication providers.');
 
-    $account = $this->drupalCreateUser(array('access administration pages'));
-
-    $this->basicAuthGet(Url::fromRoute('system.admin'), $account->getUsername(), $account->pass_raw);
-    $this->assertNoLink('Log out', 0, 'User is not logged in');
-    $this->assertResponse('403', 'No basic authentication for routes not explicitly defining authentication providers.');
     $this->curlClose();
   }
 
diff --git a/core/modules/rest/rest.services.yml b/core/modules/rest/rest.services.yml
index 14e4ab2..bfba7bb 100644
--- a/core/modules/rest/rest.services.yml
+++ b/core/modules/rest/rest.services.yml
@@ -11,6 +11,7 @@ services:
     arguments: [rest]
   access_check.rest.csrf:
     class: Drupal\rest\Access\CSRFAccessCheck
+    arguments: ['@session_configuration']
     tags:
       - { name: access_check }
   rest.link_manager:
diff --git a/core/modules/rest/src/Access/CSRFAccessCheck.php b/core/modules/rest/src/Access/CSRFAccessCheck.php
index 563a0a4..2e39c61 100644
--- a/core/modules/rest/src/Access/CSRFAccessCheck.php
+++ b/core/modules/rest/src/Access/CSRFAccessCheck.php
@@ -10,6 +10,7 @@
 use Drupal\Core\Access\AccessCheckInterface;
 use Drupal\Core\Access\AccessResult;
 use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\Session\SessionConfigurationInterface;
 use Symfony\Component\Routing\Route;
 use Symfony\Component\HttpFoundation\Request;
 
@@ -19,6 +20,23 @@
 class CSRFAccessCheck implements AccessCheckInterface {
 
   /**
+   * The session configuration.
+   *
+   * @var \Drupal\Core\Session\SessionConfigurationInterface
+   */
+  protected $sessionConfiguration;
+
+  /**
+   * Constructs a new rest CSRF access check.
+   *
+   * @param \Drupal\Core\Session\SessionConfigurationInterface $session_configuration
+   *   The session configuration.
+   */
+  public function __construct(SessionConfigurationInterface $session_configuration) {
+    $this->sessionConfiguration = $session_configuration;
+  }
+
+  /**
    * Implements AccessCheckInterface::applies().
    */
   public function applies(Route $route) {
@@ -54,7 +72,6 @@ public function applies(Route $route) {
    */
   public function access(Request $request, AccountInterface $account) {
     $method = $request->getMethod();
-    $cookie = $request->attributes->get('_authentication_provider') == 'cookie';
 
     // This check only applies if
     // 1. this is a write operation
@@ -62,7 +79,7 @@ public function access(Request $request, AccountInterface $account) {
     // 3. the request comes with a session cookie.
     if (!in_array($method, array('GET', 'HEAD', 'OPTIONS', 'TRACE'))
       && $account->isAuthenticated()
-      && $cookie
+      && $this->sessionConfiguration->hasSession($request)
     ) {
       $csrf_token = $request->headers->get('X-CSRF-Token');
       if (!\Drupal::csrfToken()->validate($csrf_token, 'rest')) {
@@ -72,4 +89,5 @@ public function access(Request $request, AccountInterface $account) {
     // Let other access checkers decide if the request is legit.
     return AccessResult::allowed()->setCacheable(FALSE);
   }
+
 }
diff --git a/core/modules/rest/src/Tests/AuthTest.php b/core/modules/rest/src/Tests/AuthTest.php
index c8a8e3b..1b576c4 100644
--- a/core/modules/rest/src/Tests/AuthTest.php
+++ b/core/modules/rest/src/Tests/AuthTest.php
@@ -51,12 +51,12 @@ public function testRead() {
     $permissions = $this->entityPermissions($entity_type, 'view');
     $permissions[] = 'restful get entity:' . $entity_type;
     $account = $this->drupalCreateUser($permissions);
-    $this->drupalLogin($account);
 
-    // Try to read the resource with session cookie authentication, which is
-    // not enabled and should not work.
+    // Read the resource with session cookie authentication.
+    $this->drupalLogin($account);
     $this->httpRequest($entity->urlInfo(), 'GET', NULL, $this->defaultMimeType);
-    $this->assertResponse('401', 'HTTP response code is 401 when the request is authenticated but not authorized.');
+    $this->assertResponse('200', 'HTTP response code is 200 for successfully authorized requests.');
+    $this->drupalLogout();
 
     // Ensure that cURL settings/headers aren't carried over to next request.
     unset($this->curlHandle);
diff --git a/core/modules/rest/src/Tests/CsrfTest.php b/core/modules/rest/src/Tests/CsrfTest.php
index d44d787..a686f448 100644
--- a/core/modules/rest/src/Tests/CsrfTest.php
+++ b/core/modules/rest/src/Tests/CsrfTest.php
@@ -61,9 +61,6 @@ protected function setUp() {
    * Tests that CSRF check is not triggered for Basic Auth requests.
    */
   public function testBasicAuth() {
-    // Login so the session cookie is sent in addition to the basic auth header.
-    $this->drupalLogin($this->account);
-
     $curl_options = $this->getCurlOptions();
     $curl_options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
     $curl_options[CURLOPT_USERPWD] = $this->account->getUsername() . ':' . $this->account->pass_raw;
diff --git a/core/modules/user/user.services.yml b/core/modules/user/user.services.yml
index 8a4f4f0..02a4faf 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: ['@session_configuration']
     tags:
       - { name: authentication_provider, priority: 0 }
   cache_context.user:
