You can do customer logged in Programmatically using Magento 2.
You required only Customer id to logged-in customer programmatically without going to the login page.
You need to first get Customer object using CustomerRepositoryInterface interface. Use Customer Object to customer session with setCustomerDataAsLoggedIn function.
<?php use Exception; use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\Exception\NoSuchEntityException; class CustomerLogin { public function __construct( CustomerRepositoryInterface $customerRepository, CustomerSession $customerSession ) { $this->customerRepository = $customerRepository; $this->customerSession = $customerSession; } /** * Login Customer by Customer Id * * @param int $customerId * @return bool * @throws Exception */ public function loginCustomerById(int $customerId) { try { // @var CustomerRepositoryInterface $customer $customer = $this->customerRepository->getById($customerId); } catch (NoSuchEntityException $exception) { throw new Exception(__('The wrong customer account is specified.')); } $this->customerSession->setCustomerDataAsLoggedIn($customer); return true; } }
Using the above way, You can do Programmatically customer login by customer id.
Pass Customer Id in above function to login Customer.
Check Customer Logout programmatically in Magento 2.