A plugin for Craft CMS that provides HTTP Basic Authentication (BasicAuth) within templates.
- Craft CMS >= 4.0.0
Open your terminal and go to your Craft project:
cd /path/to/project
composer require codemonauts/craft-basicauth
./craft install/plugin basicauth
I you are using Apache to host your CraftCMS, you have to tell Apache to pass the Authorization
header (which contains the basic auth data) to PHP (See the Dokumenation). Otherwise Craft will never see any credentials and will continue to show you the dialog to enter your username and password. This can either be set directly in the Apache config file or in your .htaccess
:
CGIPassAuth on
On the settings page in the control panel you can add credentials to use for authentication.
You can add a list of IP addresses and subnets (v4 and v6) that have access without any credentials. Use the CIDR notation for subnets.
These settings supports the project config if enabled.
In your templates you can require BasicAuth:
{% basicauth require valid env "stage" %}
The {% basicauth %}
tag supports the following parameters:`
This specifies the type of check to be made. You can check against a single user
, a group
of user, any valid
user and also accept any
provided credentials.
{# require a single user #}
{% basicauth require user "bob" %}
{# require the user to be a member of a group #}
{% basicauth require group "admins" %}
{# accept any valid credentials #}
{% basicauth require valid %}
{# accept any credentials without checking them #}
{% basicauth require any %}
This parameter is required.
This specifies the site handle for which the authentication should be made. The Authentication is only enforced when the current site handle is the same as specified.
{# require the user "bob" if the current site handle is "acme" #}
{% basicauth require user "bob" site "acme" %}
This specifies the environment for which the authentication should be made. The Authentication is only enforced when the current environment is the same as specified.
{# require the user to be a member of the group "customer" if the current environment is "stage" #}
{% basicauth require group "customer" env "stage" %}
Only activates the BasicAuth if a certain condition is met.
{% basicauth require valid if craft.app.request.isMobileBrowser() %}
This plugin provides two global variables with the credentials of the user:
<p>Hello {{ basicAuthUsername }}!</p>
<p>Your password is: {{ basicAuthPassword }}</p>
May you ask yourself why you should use this plugin and not the Basic Authentication provided by the webserver? Here are some aspects:
- You have full control of the Basic Authentication without your DevOps friends.
- You can add the
{% basicauth %}
wherever you need it: In your central layout for all pages or only in one special template with some fancy conditions. - You can use conditions from Craft. For example:
{% basicauth require valid if not currentUser %}
With ❤ by codemonauts