1

In magento 2 customer login programatically using email and password?

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 = "customerEmail@example.com"; // 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("test@m2s.com"); 
$this->customerSession->setCustomerAsLoggedIn($customer);

if($this->customerSession->isLoggedIn()) {
    echo "Customer Logged in";
}else{
    echo "customer is not Logged in";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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