Magento 2 allows customers to log in from the store’s frontend, and the admin can also handle customers from the backend.
But, what if you want your customers to log in to the Magento 2 store using only the Email ID?
The below solution allows facilitating login customer programmatically without password in Magento 2.
You can use this login method if you offer Magento extensions and want to show the demo store where the users can directly log in without having to remember a password.
Also, if you are developing a login module using which the customer can log in with just a click or by only entering the Email ID, you may find this solution helpful.
In all these scenarios, offering an easy login where users can have quick access to the store only contributes to a better user experience and thus benefits your business!
Method to Login Customer Programmatically Without Password in Magento 2
Use the below code in your controller file.
<?php
namespace Vendor\Module\Controller;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\Session;
protected $session;
protected $customerFactory;
public function __construct(
Session $session,
CustomerFactory $customerFactory
)
{
$this->session = $session;
$this->customerFactory = $customerFactory;
}
$customer = $this->customerFactory->create();
$loadCustomer = $customer->loadByEmail($email);
$this->session->setCustomerAsLoggedIn($loadCustomer);
In the $email variable, enter the email id of the customer you want to log in.
In case you are developing any third-party application, you can also use Magento 2 API to get customer token for login purpose.
That’s it.
Feel free to share the solution with Magento Community via social media.
Thank You.