In this article, we'll explain how to apply basic authentication using username and password. In Caddy, we can protect pages using the basic authentication.
1. Generate hash password
First, we'll generate hash password using Caddy command.
It is the Convenient way to hash a plaintext password. The resulting hash is written to stdout as a format usable directly in your Caddy config. Execute following command:
caddy hash-password
It will ask you to enter the password. It is the password you want to use while login. Once you enter the password, it will generate the hash. Copy the hash, we need to add it in Caddyfile.
2. Add basicauth
Next, edit Caddyfile and add a new basicauth / {}
section. Here, we need to mention username followed by hash password that we have generated with the previous command. Use your favorite editor and edit Caddyfile
vi /etc/caddy/Caddyfile
Add following lines.
basicauth / {
admin $2a$14$753B84qUtsEgvI4DGEmPWOizFB7o96uJU2J5orrnYZVSBmgFY78yy
}
Note: Replace the admin with your desired username and the hash we have generated using previous command.
It should look like following (It may look different in you file but the basicauth should add in :80 or your domain { here }):
:80 {
root * /usr/share/hostnextra.com/
file_server
basicauth / {
admin $2a$14$753B84qUtsEgvI4DGEmPWOizFB7o96uJU2J5orrnYZVSBmgFY78yy
}
}
Save and exit the Caddyfile.
3. Test and reload
Once we finish with the configuration, we need to test it first and reload the configuration. Execute following command to test/validate the configuration to check if there are any errors:
caddy validate
If there are no errors, go ahead and reload the Caddy using following command:
sudo caddy reload
Finally, navigate your browser and access your website. It will ask to enter the username and password.
http://domain-name
That's it, we have seen how to apply basic authentication in Caddy.