Securing endpoints in NGINX with Basic Authentication
NGINX Basics
Let’s begin by stating that Basic Authentication is likely not the authentication method you’re looking for. It has a number of shortcomings, not least of which is it transmits the password.
Granted, it base64 encodes the username and password first but this is reversible encoding.
Caveats aside, it does still have its uses - perhaps you want to restrict casual access to files or web applications available on your internal network only without the complexities of OAuth, Active Directory integration, or similar.
To secure endpoints in NGINX using Basic Authentication, follow these steps:
- On the NGINX host, type the following in your terminal:
# Substitute {USERNAME} for the one you want to use e.g. 'admin'
printf "{USERNAME}:`openssl passwd -apr1`\n" >> .htpasswd
Enter an appropriate strength password when prompted. For simplicity, consider creating this file in an appropriate location e.g. /etc/nginx/sites-available
.
- Update the NGINX configuration(s) for each endpoint you wish to secure:
location / {
# Display a title on the Basic Authentication browser challenge dialog (if supported)
auth_basic "Administration Area"
# The absolute path to the .htpasswd file
auth_basic_user_file /etc/nginx/sites-available/.htpasswd;
}
- Ensure the
.htpasswd
file is readable by NGINX workers:
chmod 644 .htpasswd
- Verify the NGINX configuration and reload/restart:
sudo nginx -t -c /etc/nginx/nginx.conf
sudo service nginx reload