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->boot();
// A route is required for route matching.
$request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
$request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
$kernel->preHandle($request);
if (PHP_SAPI !== 'cli') {
$request->setSession($kernel->getContainer()->get('session'));
}
} catch (HttpExceptionInterface $e) {
$response = new Response('', $e->getStatusCode());
$response->prepare($request)->send();
exit;
}
\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');
if ($account = User::load(1)) {
\Drupal::currentUser()->setAccount($account);
// Add your code.
$response->setStatusCode(200);
$response->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.
user_login_finalize()
function, since the User module hasn't been loaded, yet.