Login programmatically as a user | Drupal 8

Login programmatically as a user

Submitted by editor on Wed, 12/09/2015 - 17:25
Question

How to login programmatically as a user  in Drupal 8 ?
How to autologin in D8?

Example:
$user = User::load($uid);
user_login_finalize($user);

Comments

Vindesh mohariya (not verified)

Mon, 08/01/2016 - 12:55

Sometimes we need to login into our Drupal site not through the regular login form. For example if we have trouble with login form or maybe we just forgot our password... Here are few ways to login into your Drupal site not through login form.

For Drupal 8 you just need to create file your_auto_login.php in the Drupal root directory, put there the next code and open this file in your browser:

<?php

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

$autoloader = require_once 'autoload.php';

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

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

// ID of the user.
$uid = THE_AUTOMATIC_USER_ID; //Do not use 1 because it is the super admin
$user = Drupal\user\Entity\User::load($uid);
user_login_finalize($user);

$response->send();

$kernel->terminate($request, $response);

Raghvendra Gupta (not verified)

Thu, 08/04/2016 - 15:00

You need to put index.php at root
$uid ='Your User ID Here';
$account = \Drupal\user\Entity\User::load($uid);
\Drupal::service('session')->migrate();
\Drupal::service('session')->set('uid', $account->id());
\Drupal::moduleHandler()->invokeAll('user_login', array($account));

or
$uid ='Your User ID Here';
$user = Drupal\user\Entity\User::load($uid);
user_login_finalize($user);

$response->send();

Add new comment