Programmatically log in a user I am trying to authenticate users as below. I don't get any error, but it doesn't log in users.
autoLogin.php is located in the root folder. Visiting http://example.com/drupal8/autoLogin.php shows me the Login required page every time.
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel-&gt;handle($request);

$uid = 1; 
$user = Drupal\user\Entity\User::load(1); 
$kernel-&gt;prepareLegacyRequest($request);
user_login_finalize($user);
$response-&gt;send();
$kernel-&gt;terminate($request, $response);
The code shown in the question would throw an error about user_login_finalize() not being defined. The code isn't loading the User module and the DrupalKernel class doesn't load any module.
I generally use the code shown in authorize.php as guideline on how to bootstrap and programmatically log in a user. In this case, to programmatically log in the user whose ID is 1, I would use the following code.
use Drupal\Core\DrupalKernel;
use Drupal\user\Entity\User;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Route;

$autoloader = (require_once 'autoload.php');

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel-&gt;boot();

  // A route is required for route matching.
  $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');
if ($account = User::load(1)) {
  \Drupal::currentUser()-&gt;setAccount($account);
  // Add your code.
  $response-&gt;setStatusCode(200);
  $response-&gt;send();
}  

Since it seems you are trying to access a specific page after logging in the user #1, it's probable you need to change the two lines following the A route is required for route matching. comment and use a different route name.