Skip to content

Instantly share code, notes, and snippets.

@shapiromatron
Last active July 22, 2021 16:50
Show Gist options
  • Select an option

  • Save shapiromatron/eff07a1fd437140e64e664a576c49b28 to your computer and use it in GitHub Desktop.

Select an option

Save shapiromatron/eff07a1fd437140e64e664a576c49b28 to your computer and use it in GitHub Desktop.
adding HTTP Basic Authentication to an nginx container

containerized nginx with HTTP Basic Authentication

This demonstrates adding HTTP Basic Authentication to an nginx container, using instructions from the nginx website.

To run the demo, all you'll need is docker and docker-compose.

To build the container:

docker-compose build
docker-compose up -d

To test the container:

Open up a browser and navigate to http://127.0.0.1:9000/. The default username and password is myusername and mypassword, respectively. It's recommended to use an incognito browser for testing. To reset chrome when testing chrome://restart; but note that this is a complete browser restart and logout...

To generate new passwords, edit the htpasswd that's created when building the container.

# login to the container
docker-compose exec nginx-pw sh

# change a password, view, and exit
htpasswd -B /etc/nginx/conf/htpasswd myusername
cat /etc/nginx/conf/htpasswd
exit

To shutdown containers:

docker-compose down

Integrating with python

To integrate with a python, using requests:

import requests

sess = requests.Session()

# 401 authorization required
print(sess.get('http://127.0.0.1:9000').text)

# attach authentication; success!
sess.auth = ('myusername', 'mypassword')
print(sess.get('http://127.0.0.1:9000').text)
version: '3'
services:
nginx-pw:
build: .
ports:
- "0.0.0.0:9000:9000"
FROM nginx:1.20-alpine
RUN apk --update --no-cache add apache2-utils
COPY nginx.conf /etc/nginx/nginx.conf
COPY index.html /public/data/index.html
COPY htpasswd /etc/nginx/conf/htpasswd
myusername:$2y$05$Jtdrtr7O.YOtyijSMgfmM.v6Bn7ra.RsRMHA1oxQgd3Ssz8LGApVq
<html>
<body>
<p>Hello password protection.</p>
</body>
</html>
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
server {
listen 9000;
charset utf-8;
root /public/data;
# add HTTP password protection
auth_basic "Password protected";
auth_basic_user_file /etc/nginx/conf/htpasswd;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment