4

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?

  • 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 '17 at 10:58
  • 1
    Can you check if that helps: Log a user in manually, get session. – kenorb Nov 20 '17 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 '17 at 11:38
  • 1
    Get rid of the exit – Kevin Nov 20 '17 at 14:38
6

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.

  • 1
    Hey Jhonatan, why delete user_login_finalize, when then in your complete example again adding it? – leymannx Mar 2 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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