You can achieve the requirement by creating a module with following steps:
Step 1: Create registration.php under
app/code/STech/LoginProduct/registration.php
with below content:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'STech_LoginProduct',
__DIR__
);
Step 2: Create module.xml under
app/code/STech/LoginProduct/etc/module.xml
with below content:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="STech_LoginProduct" setup_version="0.0.1">
<sequence>
<module name="Magento_Backend"/>
<module name="Magento_Catalog"/>
<module name="Magento_Customer"/>
</sequence>
</module>
</config>
Step 3: Create di.xml under
app/code/STech/LoginProduct/etc/frontend/di.xml
with below content:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Controller\Product\View">
<plugin disabled="false" name="STech_Plugin_Catalog_Controller_Product_View" sortOrder="10" type="STech\LoginProduct\Plugin\Catalog\Controller\Product\View"/>
</type>
</config>
Step 4: Create View.php under
app/code/STech/LoginProduct/Plugin/Catalog/Controller/Product/View.php
with below content:
<?php
namespace STech\LoginProduct\Plugin\Catalog\Controller\Product;
class View
{
protected $customerSession;
protected $_urlInterface;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\UrlInterface $urlInterface
){
$this->customerSession = $customerSession;
$this->_urlInterface = $urlInterface;
}
public function aroundExecute(
\Magento\Catalog\Controller\Product\View $subject,
\Closure $proceed
) {
if (!$this->customerSession->isLoggedin()) {
$this->customerSession->setAfterAuthUrl($this->_urlInterface->getCurrentUrl());
$this->customerSession->authenticate();
}
return $proceed();
}
}
Now run the below commands:
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
Thats it!