1

In magento 2 customer login programatically using email and password?

2 Answers 2

1

Try this

<?php

...

private $customer;
private $customerSession;

public function __construct(
    ...
    \Magento\Customer\Model\Customer $customer,
    \Magento\Customer\Model\Session $customerSession
) {
    $this->customer = $customer;
    $this->customerSession = $customerSession;
    ...
}

... 

$customerEmail = "[email protected]"; // add customer email address
$websiteId = "1"; // add your website id

$customer = $this->customer;
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($customerEmail);

$this->customerSession->setCustomerAsLoggedIn($customer);

echo "customer is logged in";
1
protected $customer;
protected $customerSession;

public function __construct(...
    \Magento\Customer\Model\Customer $customer,
    \Magento\Customer\Model\Session $customerSession) {
    ...
    $this->customer = $customer;
    $this->customerSession = $customerSession;
    ...
}
...    
$customer = $this->customer->loadByEmail("[email protected]"); 
$this->customerSession->setCustomerAsLoggedIn($customer);

if($this->customerSession->isLoggedIn()) {
    echo "Customer Logged in";
}else{
    echo "customer is not Logged in";
}
1
  • You are missing a password check.
    – Black
    Apr 1, 2022 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.