5

I am trying to login users programmatically in Drupal 8. Here goes my code:

if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
  exit(0);
}

I am getting the message 'Session opened for...' in watchdog. But the user is not logged in. Can someone tell me whats wrong with my code?

5
  • 1
    Can you confirm your domain got the dot (.)? And your $base_url is set correctly or unset in the settings file?
    – kenorb
    Nov 20, 2017 at 10:58
  • 1
    Can you check if that helps: Log a user in manually, get session.
    – kenorb
    Nov 20, 2017 at 10:59
  • 2
    The default auth is done via cookies(session) so probably the code is blocking the setcookie or something(the redirect response).
    – user21641
    Nov 20, 2017 at 11:38
  • 1
    Get rid of the exit
    – Kevin
    Nov 20, 2017 at 14:38
  • I'm also facing the same issue, did you find the solution? @romisha-aggarwal
    – Kalidasan
    Jan 11, 2021 at 13:40

2 Answers 2

8

your code is Ok.

just add the following namespace:

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

delete in your code:

 user_login_finalize($user);

and

 exit(0);

A complete example would be.

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

$uid=1;

if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
ksm($user);
}

if you have installed the

devel

module and the

Kint

submodule, You can use the function

ksm()

, to show the information of a variable.

2
  • 4
    Hey Jhonatan, why delete user_login_finalize, when then in your complete example again adding it?
    – leymannx
    Mar 2, 2019 at 20:09
  • use XDebug instead devel
    – user83311
    Oct 28, 2019 at 9:16
1

Here is the full code that you can paste into a new file and run

<?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.
// REPLACE WITH WHATEVER ID YOU WANT TO LOGIN AS;
$uid = 100; 
$user = Drupal\user\Entity\User::load($uid);

// This is required to call user_login_finalize here.
$kernel->prepareLegacyRequest($request);
user_login_finalize($user);

$response->send();

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

Ref: http://www.drupal8.ovh/en/tutoriels/76/login-programmatically-as-a-user

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.