How to Login Customer Programmatically without Password in Magento 2

How to Login Customer Programmatically without Password in Magento 2

Sometimes you require to create customer programatically and login it without password in Magento 2. In many cases where the login is not important and it is just required to check the functionality or to follow a process, you require quick login. One of the best use when you want to show users with Magento extensions demo where login is needed.

Here, the user experience will get worse if you force them to remember password or enter it. This may lead users to leave website and thus increases bounce rate of your website. Here, I have come up with a code trick to skip password and login customer programmatically.

First you need to use 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("johndoe@example.com"); 
$this->_customerSession->setCustomerAsLoggedIn($customer);

And you are done. Hope this guide has enough helped you to skip password and auto login customer programmatically. Let me know if you have any issue or want to give any suggestions through commenting.

Previous Article

How to Filter UI Component Grid Collection in Magento 2

Next Article

How to Install Magento SUPEE 9767 Version 2 With or Without SSH

Write a Comment
  1. Hello, i’m looking to connect a customer by mail and without password. How can i set the session ? This code just connect for current page or everypage ? Where i place it ? controller or block ?

    Regards !

    1. Hello,
      This code sets the customer as logged in customer by using his email. You need to place this code as per your requirement. You have to set this code in the constructor of say helper, model, controller or block.

      Thanks

  2. Hello, i’m looking to connect a customer by mail and without password. How can i set the session ? This code just connect for current page or everypage ? Where i place it ? controller or block ?

    Regards !

    1. Hello,
      This code sets the customer as logged in customer by using his email. You need to place this code as per your requirement. You have to set this code in the constructor of say helper, model, controller or block.

      Thanks

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨