Customer Authentication in Magento 2 is required when we have to check the customer is a guest user or a login user.
There are many occasions when we have to check the customer is login or not, and based on the login customer, only we have to show a specific page; otherwise, redirect it to the login page.
To verify whether it’s a login customer or not,
use MagentoCustomerModelSession Class and add the Customer Session class to the __construct() method of your Controller.
<?php
namespace MagemonkeysFavoriteListControllerIndex;
use MagentoFrameworkAppAction;
use MagentoCustomerModelSession;
use MagentoFrameworkViewResultPage;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkControllerResultFactory;
class Index extends Action
{
/**
* @var Session
*/
protected $customerSession;
public function __construct(
Context $context,
Session $customerSession
) {
$this->customerSession = $customerSession;
parent::__construct($context);
}
/**
* Prepare wishlist for share
*
* @return ResultInterface
*/
public function execute()
{
if (!$this->customerSession->authenticate()) {
/** @var Page $resultPage */
$result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$result->setPath('customer/account/login');
return $result;
}
// do your logic here
}
}
Using this approach, we can check the customer is a login customer or not.

