Site icon MageComp Blog

How to Login Customer Programmatically without Password in Magento 2

How to Login Customer Programmatically without Password in Magento 2

How to Login Customer Programmatically without Password in Magento 2

Sometimes you require to create customer programatically and login it without password in Magento 2. In many cases where the login is not important and it is just required to check the functionality or to follow a process, you require quick login. One of the best use when you want to show users with Magento extensions demo where login is needed.

Here, the user experience will get worse if you force them to remember password or enter it. This may lead users to leave website and thus increases bounce rate of your website. Here, I have come up with a code trick to skip password and login customer programmatically.

First you need to use dependency injection to inject the following classes in your constructor.

protected $_customer;
protected $_customerSession;

public function _construct(...
                         \Magento\Customer\Model\Customer $customer,
                         \Magento\Customer\Model\Session $customerSession) {
    ...
    $this->_customer = $customer;
    $this->_customerSession = $customerSession;
    ...
}

Then in your code you can do:

$customer = $this->_customer->loadByEmail("johndoe@example.com"); 
$this->_customerSession->setCustomerAsLoggedIn($customer);

And you are done. Hope this guide has enough helped you to skip password and auto login customer programmatically. Let me know if you have any issue or want to give any suggestions through commenting.

Exit mobile version