Introduction

When it comes to sharing password or storing password, putting some form of password verification in place can be an essential part of sharing content with accredited users. Every application on the internet has some parts in it that an anonymous user should not access. For example, a directory containing confidential documents like PDFs, Docs and sheets. But, there is a way to protect these directories at server level with Apache htpasswd.

So, What is htpasswd? It is an Apache utility that allows you to protect a part of your application or the whole application with username and password at the server level. htpasswd is used to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. htpasswd encrypts passwords using either bcrypt, a version of MD5 modified for Apache, SHA1, or the system’s crypt() routine. Files managed by htpasswd may contain a mixture of different encoding types of passwords; some user records may have bcrypt or MD5-encrypted passwords while others in the same file may have passwords encrypted with crypt(). Passwords will be stored in an encrypted format and the username will be in plaintext.

How to setup and use htpasswd

A.) On linux htpasswd can be installed as part of “apache2-utils” package. This can be done by following below command :

  1. Install apache2 package
    sudo apt install apache2-utils
  2. Create apache htpasswd file using below command, ‘-c’ option creates a new file and stores the values.
    htpasswd -c /installers/.htpasswd <username>

B.) I personally prefer using containers wherever I can, this gives me the flexibility to manage resources effectively. If you would like to run it as a container for one-time use, you can use the official Apache httpd image version 2. We can use any other version as well. This step assumes you have docker installed on your machine, if you don’t have docker installed. Follow this blog to setup docker on your machine. As an output, you will have the htpasswd file under the /blog/docker/auth folder. You can change these parameters to suit your need.

mkdir /blog
mkdir /blog/docker
mkdir /blog/docker/auth
 docker run \
  --entrypoint htpasswd \
  httpd:2 -Bbn susheel BlogTestPassWord > /blog/docker/auth/htpasswd

How to validate your htpasswd values :

As mentioned previously htpasswd file stores username as plaintext but password as an encrypted format, which is why we will have to use htpasswd utility to validate our password against a file, as you notice I used BlogTestPassWord password for user susheel in this step.

We can use htpasswd -vb option to validate our inputs against the htpasswd file. Use this link to check options available for htpasswd command. I first use the wrong password and then the correct one which confirms the password is correct.