Login programmatically in Magento 2 .
You required only Customer id or Customer email to logged-in customer programmatically without going to the login page.
Customer id or customer email require to load customer.
You need to first get Customer object using CustomerFactory .
Use Customer Object to customer session with setCustomerDataAsLoggedIn function.
This method also known as customer loggen in forcefully without having customer password./
Write below code into PHTML file or other also do this by inject class(di method)
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory'); $customer = $customerFactory->create(); //$customer->loadByEmail('[email protected]');// load customer by email address $customer->load('1');// load customer by using ID $customerSession = $objectManager->get('Magento\Customer\Model\Session'); $customerSession->setCustomerAsLoggedIn($customer); if($customerSession->isLoggedIn()) { echo $customerSession->getCustomer()->getId(); // get Customer Id echo $customerSession->getCustomer()->getName(); // get Full Name echo $customerSession->getCustomer()->getEmail(); // get Email Name echo $customerSession->getCustomer()->getGroupId(); // get Customer Group Id }
Using 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("[email protected]"); $this->_customerSession->setCustomerAsLoggedIn($customer); echo $customerSession->getCustomer()->getId();
Admin login programmatically in magento 2
Like us on Facebook and Linkedin for more updates.