In Magento 2, customers can log in from the website’s frontend by themselves by using username and password, and the admin can also handle customers from the backend manually.
But, when you are required to login customer, but you don’t have password, or you want to login any customer by only email then you can use this method.
To login any customer without password Programmatically, you have to use below block of code in your controller file as below :
Here, we have used Magento\Customer\Model\CustomerFactory instance and created it’s object($customerFactory) then used Magento\Customer\Model\Session instance and created it’s object($customerSession) and in last we have used Magento\Store\Model\StoreManagerInterface and created it’s object($storeManager).
<?php namespace Mageants\Blog\Controller\Index; use Magento\Customer\Model\CustomerFactory; use Magento\Customer\Model\Session; use Magento\Store\Model\StoreManagerInterface; class Test extends \Magento\Framework\App\Action\Action { protected $customerFactory; protected $customerSession; protected $storeManager; public function __construct( ....... CustomerFactory $customerFactory, Session $customerSession, StoreManagerInterface $storeManager, ...... ) { ....... $this->customerFactory = $customerFactory; $this->customerSession = $customerSession; $this->storeManager = $storeManager; ...... } public function execute() { $email = "roni_cost@example.com"; // set the customer email id $websiteId =$this->storeManager->getStore()->getWebsiteId(); // get current websiteid $customer = $this->customerFactory->create(); $loadCustomer = $customer->setWebsiteId($websiteId)->loadByEmail($email); // load customer by using websiteid and email $this->customerSession->setCustomerAsLoggedIn($loadCustomer); // set the customer session as login } } |
When you call above controller then the customer who has email id ‘roni_cost@example.com’ he will be logged in your website without giving password programmatically.
In this way, we can login any customer to our website by just having customer’s email id by programmatically.
Conclusion :
We hope above blog helps you to clearly understand how to login customer programmatically without password in Magento 2.
In case of any kind of problem with the above code implementation, you can contact us or let us know in comment section.