Skip to main content

Magento 2 Frontend Customer Force Login Module

· 2 min read
Florian Horn

The administrative view of Magento 2 forces you to login, but in the website view the visitor can navigate as a guest through the pages. But if you do not wish to allow guest visitors to see your page without registration a valid login, Magento 2 leaves you on your own.

The solution of our Frontend Customer Force Login module is rather simple, listing to some events and redirect to the login page, if the user is not logged in. We have to add some urls to a ignore list, to avoid negative sideffects in the administrative backend of Magento 2 and avoid infinity redirect loops.

Simply install the module via Composer:

composer require bitexpert/magento2-force-customer-login

It is possible to extend the whitelist for ignored urls in your DI configuration:

<type name="\bitExpert\ForceCustomerLogin\Controller\LoginCheck">
<arguments>
<argument name="ignoreUrls" xsi:type="array">
<item name="admin_area" xsi:type="string">
^/admin/?.*$
</item>
<item name="rest_api" xsi:type="string">
^/rest/?.*$
</item>
<item name="customer_account_login" xsi:type="string">
^/customer/account/login/?$
</item>
<item name="customer_account_logout" xsi:type="string">
^/customer/account/logout/?$
</item>
<item name="customer_account_logout_success" xsi:type="string">
^/customer/account/logoutSuccess/?$
</item>
<item name="customer_account_create" xsi:type="string">
^/customer/account/create/?$
</item>
<item name="customer_account_create_password" xsi:type="string">
^/customer/account/createPassword/?.*$
</item>
<item name="customer_account_forgot_password" xsi:type="string">
^/customer/account/forgotpassword/?.*$
</item>
<item name="customer_account_forgot_password_post" xsi:type="string">
^/customer/account/forgotpasswordpost/?.*$
</item>
<item name="customer_section_load" xsi:type="string">
^/customer/section/load/?$
</item>
<item name="contact_us" xsi:type="string">
^/contact/?$
</item>
<item name="help" xsi:type="string">
^/help/?$
</item>
</argument>
<argument name="targetUrl" xsi:type="string">
customer/account/login
</argument>
</arguments>
</type