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.
1 2 3 4 5 6 7 8 9 10 11 |
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:
1 2 |
$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.
Hello, i’m looking to connect a customer by mail and without password. How can i set the session ? This code just connect for current page or everypage ? Where i place it ? controller or block ?
Regards !
Hello,
This code sets the customer as logged in customer by using his email. You need to place this code as per your requirement. You have to set this code in the constructor of say helper, model, controller or block.
Thanks
Hello, i’m looking to connect a customer by mail and without password. How can i set the session ? This code just connect for current page or everypage ? Where i place it ? controller or block ?
Regards !
Hello,
This code sets the customer as logged in customer by using his email. You need to place this code as per your requirement. You have to set this code in the constructor of say helper, model, controller or block.
Thanks