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 a customer, but you don’t have a password, or you want to login any customer by only email then you can use this method.
Steps to Login Customer in Magento 2 Programmatically
Step 1: Use the Right Classes
To log in a customer without password programmatically, you’ll need three main classes:
- Magento\Customer\Model\CustomerFactory → To load customer data.
- Magento\Customer\Model\Session → To set the customer session.
- Magento\Store\Model\StoreManagerInterface → To get the current website/store ID.
Step 2: Add the Code in Your Controller
Here’s a simple example you can use in your controller file:
<?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
}
}
|
Step 3: Run the Controller
Once you call this controller, Magento will automatically log in the customer with the email ID roni_cost@example.com
In this way, we can login any customer to our website by just having the customer's email programmatically.
Conclusion: Magento 2 Login Customer Programmatically
We hope the 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