Wednesday 27 February 2019

Drupal 8 login a user programatically

Question: How to login a user programmatically in Drupal 8?

Steps:

In your module, create a menu call back

example.externallogin:
  path: '/external/login/{token}'
  defaults:
    _controller: '\Drupal\example\Controller\ExamplesController::externallogin'
    _title: 'Offers'
  requirements:
    _access: 'TRUE'


in your controller,

modules/example/src/Controller/ExamplesController.php,

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

public function externallogin($token = NULL) {
$uid = 111; // Can be any valid Drupal's user id.
if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
}
return ['#type' => 'markup', '#markup' => $this->t('You are logged in')];
}

And user is logged into Drupal.

No comments:

Post a Comment

Parenting tips to inculcate learning habits in your kid

Parenting tips to inculcate learning habits in your kid Tip #1) Children do not learn things, they emitate. So, try to do things by yours...