i have an app that sends username and password to a php script. This script checks that a user exists on Drupal 8 with username and password entered but does not log the user. I need the user to log in. Can someone help me? thanks Follows script code

use Drupal\user\UserAuthInterface;
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
// Boot Drupal.
$autoloader = require __DIR__ . '/autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
// Recupero Nome utente e password
$nome_ut = $_POST['nome'];
$pass_ut = $_POST['pwd'];
// effettuo il controllo
$user_auth = \Drupal::service('user.auth');
$user_storage = \Drupal::entityTypeManager()->getStorage('user');

$accounts = $user_storage->loadByProperties(['name' => $nome_ut, 'status' => 1]);
$account = reset($accounts);

if ($account) {
    if ($user_auth->authenticate($nome_ut, $pass_ut))
    // The credentials are correct.
       $id = $user_auth->authenticate($nome_ut, $pass_ut);
       print ("Accesso riuscito!");
           // Force session start if we don't already have a session.
               $session = \Drupal::service('session');
               if (!$session->isStarted()) {
           if (\Drupal::currentUser()->isAuthenticated()) {
               // This user is logged in.
               print ("Utente Loggato");
           } else {
               // This user is not logged in.
               print ("Utente non Loggato");

1 Answer 1


Could you use a rest endpoint? Because this is already handled by drupal core. See for example this or this

Otherwise I think you're just missing user_login_finalize after your check if the user is logged in.

//Eventually redirect the user somewhere
$user_destination = \Drupal::destination()->get();
$response = new RedirectResponse($user_destination);
  • Thanks Giuseppe.... now I try May 5, 2021 at 9:47
  • But $user is??? I'll take it from the ID? May 5, 2021 at 10:03
  • Sorry, I didn't link the full API but they're easily accessible: user_login_finalize takes an UserInterface object as argument... so you can use the $account you've loaded before in your example.
    – Giuseppe
    May 5, 2021 at 13:31

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.