Login programmatically in Magento 2

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
// Load customer
$customer = $objectManager->create('Magento\Customer\Model\Customer')->load(2); //2 is Customer ID

// Load customer session
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
$customerSession->setCustomerAsLoggedIn($customer);

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

A better way nowadays with Magento 2 is:

protected $_customerFactory;
protected $_sessionFactory;

public function __construct(
    ...
    \Magento\Customer\Model\CustomerFactory $customerFactory,
    \Magento\Customer\Model\SessionFactory $sessionFactory,
    ...
)
{
    ...
    $this->_customerFactory = $customerFactory;
    $this->_sessionFactory = $sessionFactory;
    ...
}

Now lets say this is on a Magento 2 Controller, then we have the below:

public function execute()
{
    ...
    $customer = $this->_customerFactory->create()->load($id) //$id is the 
    customer id you want to load
    $sessionManager = $this->_sessionFactory->create();
    $sessionManager->setCustomerAsLoggedIn($customer);
    ...
}

It is always best practice to use dependency injection to retrieve either model factories or interfaces for the tool you want to use instead of getting object manager instances.


Take a look at app/code/Magento/Customer/Controller/Account/LoginPost.php

class LoginPost extends \Magento\Customer\Controller\AbstractAccount
{

  ....

  public function execute()
  {
    if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('*/*/');
        return $resultRedirect;
    }

    if ($this->getRequest()->isPost()) {
        $login = $this->getRequest()->getPost('login');
        if (!empty($login['username']) && !empty($login['password'])) {
            try {
                $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                $this->session->setCustomerDataAsLoggedIn($customer);
                $this->session->regenerateId();
  ....

Tags:

Magento2