Skip to content

Instantly share code, notes, and snippets.

@mauler
Forked from fxsjy/SimpleAuthServer.py
Last active June 15, 2026 00:44
Show Gist options
  • Select an option

  • Save mauler/593caee043f5fe4623732b4db5145a82 to your computer and use it in GitHub Desktop.

Select an option

Save mauler/593caee043f5fe4623732b4db5145a82 to your computer and use it in GitHub Desktop.
Python3 http.server supporting basic HTTP Auth (username/password)
# Extended python -m http.serve with --username and --password parameters for
# basic auth, based on https://gist.github.com/fxsjy/5465353
from functools import partial
from http.server import SimpleHTTPRequestHandler, test
import base64
import os
class AuthHTTPRequestHandler(SimpleHTTPRequestHandler):
""" Main class to present webpages and authentication. """
def __init__(self, *args, **kwargs):
username = kwargs.pop("username")
password = kwargs.pop("password")
self._auth = base64.b64encode(f"{username}:{password}".encode()).decode()
super().__init__(*args, **kwargs)
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_AUTHHEAD(self):
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="Test"')
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
""" Present frontpage with user authentication. """
if self.headers.get("Authorization") == None:
self.do_AUTHHEAD()
self.wfile.write(b"no auth header received")
elif self.headers.get("Authorization") == "Basic " + self._auth:
SimpleHTTPRequestHandler.do_GET(self)
else:
self.do_AUTHHEAD()
self.wfile.write(self.headers.get("Authorization").encode())
self.wfile.write(b"not authenticated")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--cgi", action="store_true", help="Run as CGI Server")
parser.add_argument(
"--bind",
"-b",
metavar="ADDRESS",
default="127.0.0.1",
help="Specify alternate bind address " "[default: all interfaces]",
)
parser.add_argument(
"--directory",
"-d",
default=os.getcwd(),
help="Specify alternative directory " "[default:current directory]",
)
parser.add_argument(
"port",
action="store",
default=8000,
type=int,
nargs="?",
help="Specify alternate port [default: 8000]",
)
parser.add_argument("--username", "-u", metavar="USERNAME")
parser.add_argument("--password", "-p", metavar="PASSWORD")
args = parser.parse_args()
handler_class = partial(
AuthHTTPRequestHandler,
username=args.username,
password=args.password,
directory=args.directory,
)
test(HandlerClass=handler_class, port=args.port, bind=args.bind)
@jenciso

jenciso commented Apr 14, 2020

Copy link
Copy Markdown

I had to change line 17 from super().__init__(*args, **kwargs) to super().__init__(*args) otherwise i received an error that the parent class got some invalid arguments. Can you confirm that or tell me why i got that error?

Yes, same here. Works if you remove it, I went ahead and did that and put it into this gist: https://gist.github.com/lionelyoung/8cad668d4d30fa392842fa08d50d2bc6

Thanks

@Christoph460

Christoph460 commented Aug 7, 2020

Copy link
Copy Markdown

@kcraft09 Setting the directory via the command line was also not working for me. I fixed it with the change of the first lines to
`

def init(self, *args, **kwargs):
username = kwargs.pop("username")
password = kwargs.pop("password")
directory = kwargs.pop("directory")

 self._auth = base64.b64encode(f"{username}:{password}".encode()).decode()
 super().__init__(*args, directory=directory)

`

@Last-Arkhangel

Copy link
Copy Markdown

Good day, everyone. Please tell me how to screw ssl (https) here. Thank.

@ebrahimiali

Copy link
Copy Markdown

Is it possible to support POST in this server too?

@thevickypedia

Copy link
Copy Markdown

Is there a way I can have this script do a timeout or close the connection?
I basically need a re-auth after a set timeout or a logout button which can terminate the session.

@mauler

mauler commented Jul 7, 2021 via email

Copy link
Copy Markdown
Author

@thevickypedia

Copy link
Copy Markdown

I think u can set something on the do_GET method. First add this to init self.timeouts = {} and on do_GET always record the first time someone (use remote address) send the Authentication header on the request (a valid one). So if it is expired, try to enforce the auth using do_AUTHHEAD Em seg., 5 de jul. de 2021 às 00:17, Vignesh Rao @.> escreveu:

@.
* commented on this gist. ------------------------------ Is there a way I can have this script do a timeout or close the connection? I basically need a re-auth after a set timeout or a logout button which can terminate the session. — You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://gist.github.com/593caee043f5fe4623732b4db5145a82#gistcomment-3802275, or unsubscribe https://github.com/notifications/unsubscribe-auth/AABZLZQVQUU3QYCKECEF4LTTWDFWBANCNFSM4JP3SNPA .

Thanks for the response, I think I figured my way out.
I'm setting the Authorization header to None at the first visit and also at given intervals so the remaining code keeps flowing.

self.headers.replace_header('Authorization', None)

@nikodemusk

Copy link
Copy Markdown

Really useful, thank you. I use it instead of password protect a directory with Nginx for a service.

@RobertNissan

Copy link
Copy Markdown

pero al iniciar la sesión en el navegador cual es el nombre de usuario y la contraseña ?

@wgetnz

wgetnz commented Feb 11, 2023

Copy link
Copy Markdown

当使用其他方法如PUT POST等,密码保护会失效

@VSharapov

Copy link
Copy Markdown

My one-liner to set the password at runtime (visible in terminal): python <(curl https://gist.githubusercontent.com/mauler/593caee043f5fe4623732b4db5145a82/raw/972eb768159f0324d12d5d52b67b8e2841f4da73/http_server_auth.py) --username=$(whoami) --password=$(head -1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment