Cannot get currentUser after custom Drupal boot I have a /foo.php on the Drupal 8 root which programmatically boots Drupal:
chdir('web');
$autoloader = require_once 'autoload.php';
$request = Request::createFromGlobals();
print_r($request-&gt;cookies);             // ... ( ... ( [SSESSabfa7...] =&gt; _Eu_28jS3Vr8Y... ))
$this-&gt;kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$this-&gt;kernel-&gt;boot();
var_dump(\Drupal::currentUser()-&gt;id()); // int(0)

$this-&gt;kernel-&gt;preHandle($request);
var_dump(\Drupal::currentUser()-&gt;id()); // int(0)

The problem is that it doesn't seem to be able to access the current user (see the var_dumps). By visiting a regular Drupal URL though (e.g at / or /about) I confirm that the session cookie is correct with a logged in user.
What do I need to do so my custom PHP script boots Drupal in a way that it can return the currently logged in user?
You have to authenticate the user. This is what a normal Drupal request would do as one of the first things after the kernel is booted:
Drupal\Core\EventSubscriber\AuthenticationSubscriber
  /**
   * Authenticates user on request.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The request event.
   *
   * @see \Drupal\Core\Authentication\AuthenticationProviderInterface::authenticate()
   */
  public function onKernelRequestAuthenticate(GetResponseEvent $event) {
    if ($event-&gt;isMasterRequest()) {
      $request = $event-&gt;getRequest();
      if ($this-&gt;authenticationProvider-&gt;applies($request)) {
        $account = $this-&gt;authenticationProvider-&gt;authenticate($request);
        if ($account) {
          $this-&gt;accountProxy-&gt;setAccount($account);
          return;
        }
      }
    }
  }

Adapting this to the procedural code:
web/foo.php
&lt;?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';
$request = Request::createFromGlobals();
print_r($request-&gt;cookies);             // ... ( ... ( [SSESSabfa7...] =&gt; _Eu_28jS3Vr8Y... ))
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel-&gt;boot();
$kernel-&gt;preHandle($request);

$container = $kernel-&gt;getContainer();
// Ensure our request includes the session.
$request-&gt;setSession($container-&gt;get('session'));
// Authenticate the user, see AuthenticationSubscriber::onKernelRequestAuthenticate().
$account = $container-&gt;get('authentication')-&gt;authenticate($request);
if ($account) {
  $container-&gt;get('current_user')-&gt;setAccount($account);
}

var_dump(\Drupal::currentUser()-&gt;id());