Allow authorization via cookies We are migrating from Drupal 7 to Drupal 8 and are currently at the last hurdle - relying on Drupal's session to authenticate for custom scripts.
Previously we used to rely on drupal_bootstrap but now I have implemented a similar Drupal 8 aware version for bootstrapping and checking the user is authenticated (and which roles they have etc) - this is broadly based on core/authorize.php.
However - this only works in the drupal root directory or the core/ directory - in every other directory this fails to authenticate the user.
I believe this is down to the routing, and authentication only working for pre-defined routes.
Specifically I want to be able to authenticate users in any script in a folder (recursively). EG

external_scripts/script1.php
external_scripts/script1.php
external_scripts/other_scripts/script3.php

How do I add a route to allow this? Or can I just bypass this route checking when using the cookie? Can I spoof the route?
&lt;?php

/**
 * @file
 * Locates the Drupal root directory and bootstraps the kernel.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\Routing\Route;

function _find_autoloader($dir) {
  $autoloadFile = $dir . '/vendor/autoload.php';
  if (file_exists($autoloadFile)) {
    return include_once($autoloadFile);
  }
  elseif (empty($dir) || $dir === DIRECTORY_SEPARATOR) {
    return FALSE;
  }
  return _find_autoloader(dirname($dir));
}

// Immediately return if classes are discoverable (already booted).
if (class_exists('\Drupal\Core\DrupalKernel') &amp;&amp; class_exists('\Drupal')) {
  return \Drupal::service('kernel');
}

$autoloader = _find_autoloader(empty($_SERVER['PWD']) ? getcwd() : $_SERVER['PWD']); // defined in start.inc
if (!$autoloader || !class_exists('\Drupal\Core\DrupalKernel')) {
  print &quot;This script must be invoked inside a Drupal 8 environment. Unable to continue.\n&quot;;
  exit();
}

const MAINTENANCE_MODE = 'update';

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel-&gt;boot();
  $request-&gt;attributes-&gt;set(RouteObjectInterface::ROUTE_OBJECT, new Route('&lt;none&gt;'));
  $request-&gt;attributes-&gt;set(RouteObjectInterface::ROUTE_NAME, '&lt;none&gt;');
  $kernel-&gt;preHandle($request);
  if (PHP_SAPI !== 'cli') {
    $request-&gt;setSession($kernel-&gt;getContainer()-&gt;get('session'));
  }
}
catch (HttpExceptionInterface $e) {
  $response = new Response('', $e-&gt;getStatusCode());
  $response-&gt;prepare($request)-&gt;send();
  exit;
}

\Drupal::moduleHandler()-&gt;addModule('system', 'core/modules/system');
\Drupal::moduleHandler()-&gt;addModule('user', 'core/modules/user');
\Drupal::moduleHandler()-&gt;load('system');
\Drupal::moduleHandler()-&gt;load('user');

$content = [];
$show_messages = TRUE;

$account = \Drupal::service('authentication')-&gt;authenticate($request);

if ($account) {
  \Drupal::currentUser()-&gt;setAccount($account);
}

var_dump(\Drupal::currentUser());
I tried many different ways of loading the user, using the session as the starting point. In every singe scenario it fell down.
So in the end I used as much of the Drupal scaffold as I could, and copied the relevant bits from the relevant classes and functions in order to control the loading of a user record in an ajax handler that exists outside of Drupal's page space.
It uses the cookie to load the session, retrieve the user id, details and roles and create an account object before setting the bootstrapped Drupal kernel current user to the account object.
We deal with access control at a higher level (relying on \Drupal::currentUser() and leveraging $user-&gt;isAuthenticated() for example) so this script gets up to a consistent point in both contexts (inside Drupal, and non-drupal pages inside the domain) for user management etc.
&lt;?php

/**
 * @file
 * Bootstraps the Drupal kernel and loads the user for the incoming request via cookie
 */

use Drupal\Core\DrupalKernel;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\UserSession;
use Symfony\Component\HttpFoundation\Request;

function _find_autoloader($dir) {
  $autoloadFile = $dir . '/vendor/autoload.php';
  if (file_exists($autoloadFile)) {
    return include_once($autoloadFile);
  }
  elseif (empty($dir) || $dir === DIRECTORY_SEPARATOR) {
    return FALSE;
  }
  return _find_autoloader(dirname($dir));
}

// Immediately return if classes are discoverable (already booted).
if (class_exists('\Drupal\Core\DrupalKernel') &amp;&amp; class_exists('\Drupal')) {
  return \Drupal::service('kernel');
}

// Load autoload
$autoloader = _find_autoloader(empty($_SERVER['PWD']) ? getcwd() : $_SERVER['PWD']); // defined in start.inc
if (!$autoloader || !class_exists('\Drupal\Core\DrupalKernel')) {
  print &quot;This script must be invoked inside a Drupal 8 environment. Unable to continue.\n&quot;;
  exit();
}

const MAINTENANCE_MODE = 'update'; // Don't bother theming

if (PHP_SAPI == 'cli') { // CLI won't have a cookie, stop now
  return;
}

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel-&gt;boot();
$connection = $kernel-&gt;getContainer()-&gt;get('database');

// Get session id from session cookie
$sid = reset($_COOKIE);

// Get uid from sessions, get user from uid
$query = $connection-&gt;queryRange('SELECT uid FROM {sessions} WHERE sid = :sid', 0, 1, [':sid' =&gt; Crypt::hashBase64($sid)]);
$uid = (string)$query-&gt;fetchField();
$values = $connection-&gt;query('SELECT * FROM {users_field_data} u WHERE u.uid = :uid AND u.default_langcode = 1', [':uid' =&gt; $uid])-&gt;fetchAssoc();

// Get roles from uid, and set account
if (!empty($values) &amp;&amp; $values['status'] == 1) {
  $rids = $connection-&gt;query('SELECT roles_target_id FROM {user__roles} WHERE entity_id = :uid', [':uid' =&gt; $values['uid']])-&gt;fetchCol();
  $values['roles'] = array_merge([AccountInterface::AUTHENTICATED_ROLE], $rids);
  $account = new UserSession($values);
  \Drupal::currentUser()-&gt;setAccount($account);
}