DEV Community

Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on

Securing Your Website with Basic Auth for NGINX

When managing NGINX-secured areas, implementing Basic Authentication is a straightforward yet effective solution. To streamline user management and password handling, we can automate the process using Bash.

It is also helps you to secure development / staging site which only certain users can access to the system / applications.

This tutorial will walk you through creating a script to automatically generate secure passwords and save them in a .htpasswd file for NGINX, including making this script flexible with configurable options.

Why Automate Basic Authentication?

NGINX’s auth_basic feature provides a simple way to password-protect areas of your web application. However, manually creating user credentials using the htpasswd command can become tedious, especially when managing multiple users. Automating this process not only saves time but also ensures password security by generating strong, random passwords.

How Does the Script Work?

This script:

  1. Accepts a username as a named argument.
  2. Automatically generates a random password for the user.
  3. Creates or updates a .htpasswd file where credentials are securely stored.
  4. Allows configuration of the credentials directory via named arguments, while using /etc/nginx/credentials as the default path.

Creating the Script

#!/bin/bash

# Default values
DIRECTORY="/etc/nginx/credentials"

# Help function
usage() {
    echo "Usage: $0 --username <username> [--directory <path_to_directory>]"
    exit 1
}

# Parse named arguments
while [ "$1" != "" ]; do
    case $1 in
        --username )           shift
                               USERNAME=$1
                               ;;
        --directory )          shift
                               DIRECTORY=$1
                               ;;
        -h | --help )          usage
                               ;;
        * )                    usage
                               ;;
    esac
    shift
done

# Check if username was provided
if [ -z "$USERNAME" ]; then
    echo "Error: --username is required."
    usage
fi

# Set the file path for the htpasswd file
HTPASSWD_FILE="$DIRECTORY/${USERNAME}_htpasswd"

# Create the directory if it doesn't exist
if [ ! -d "$DIRECTORY" ]; then
    mkdir -p "$DIRECTORY"
    echo "Directory $DIRECTORY created."
fi

# Generate a random 12-character password
PASSWORD=$(openssl rand -base64 12)

# Ensure apache2-utils (htpasswd) is installed
if ! command -v htpasswd &> /dev/null
then
    echo "apache2-utils (htpasswd) could not be found. Please install it."
    exit 1
fi

# Create or update the .htpasswd file with the username and generated password
if [ -f "$HTPASSWD_FILE" ]; then
    htpasswd -b "$HTPASSWD_FILE" "$USERNAME" "$PASSWORD"
else
    htpasswd -cb "$HTPASSWD_FILE" "$USERNAME" "$PASSWORD"
fi

# Set the file permissions to -rw-r--r-- (644)
chmod 644 "$HTPASSWD_FILE"

# Output the username and generated password
echo "Username: $USERNAME"
echo "Password: $PASSWORD"
echo ".htpasswd file created at $HTPASSWD_FILE"
Enter fullscreen mode Exit fullscreen mode

Using the Script

  1. Default Credentials Directory:

By default, the script will store the .htpasswd file under /etc/nginx/credentials.

./create_htpasswd.sh --username asset-tracker
Enter fullscreen mode Exit fullscreen mode

The above command creates a user asset-tracker with a randomly generated password and stores the credentials in /etc/nginx/credentials/asset-tracker_htpasswd.

  1. Custom Credentials Directory:

You can change the location where the .htpasswd file is stored by using the --directory argument:

./create_htpasswd.sh --username asset-tracker --directory /custom/path/to/credentials
Enter fullscreen mode Exit fullscreen mode

This flexibility allows you to organize your credential files based on your infrastructure needs.

Updating NGINX Configuration to Use the Generated Credentials

Now that you have the .htpasswd file created, you can use it in your NGINX configuration to protect certain locations or the entire site.

  1. Open Your NGINX Configuration File: You can either modify the main NGINX configuration file (usually located at /etc/nginx/nginx.conf) or the configuration file for your specific site (e.g., /etc/nginx/sites-available/your-site).
   sudo nano /etc/nginx/sites-available/your-site
Enter fullscreen mode Exit fullscreen mode
  1. Add Basic Authentication to a Location Block: Add the following lines to the location block you want to protect. You can also apply this to the root location (/) if you want to protect the entire site.
   server {
       listen 80;
       server_name your-domain.com;

       location /protected-area/ {
           auth_basic           "Restricted Area";
           auth_basic_user_file /etc/nginx/credentials/asset-tracker_htpasswd;
       }
   }
Enter fullscreen mode Exit fullscreen mode
  • auth_basic: This directive specifies that Basic Authentication should be used. The string "Restricted Area" is the realm name, which will be displayed in the login prompt.
  • auth_basic_user_file: This directive points to the .htpasswd file that was generated using the script.
  1. Test NGINX Configuration: After updating the configuration, it’s essential to test NGINX to ensure there are no syntax errors:
   sudo nginx -t
Enter fullscreen mode Exit fullscreen mode
  1. Reload NGINX: Once the test is successful, reload NGINX to apply the changes:
   sudo systemctl reload nginx
Enter fullscreen mode Exit fullscreen mode
  1. Access the Protected Area: When you navigate to the protected URL (e.g., http://your-domain.com/protected-area/), NGINX will prompt for a username and password. Enter the credentials generated by the script, and you’ll be granted access.

Why Use This Script?

  • Automation: No need to manually create or update .htpasswd files every time a user is added or modified.
  • Security: Automatically generates strong, random passwords using openssl.
  • Flexibility: Allows custom storage paths for credential files, ideal for different environments or NGINX setups.
  • Easy Integration: Directly integrates with NGINX’s Basic Authentication mechanism.

Wrapping Up

Automating the creation of .htpasswd files simplifies user management in NGINX’s Basic Authentication. By incorporating password generation, directory configuration, and easy usage into a script, you can enhance your web security practices with minimal manual effort. Additionally, updating your NGINX configuration to use the generated .htpasswd file ensures that your protected areas are secured with user credentials.

Download the script, configure your NGINX, and make managing your secured areas seamless!

Top comments (0)