Programmatically User login not working 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()-&gt;get();
  $response = new RedirectResponse($user_destination);
  $response-&gt;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?
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()-&gt;get();
  $response = new RedirectResponse($user_destination);
  $response-&gt;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.