Skip to content

Instantly share code, notes, and snippets.

@lionelyoung
Forked from mauler/http_server_auth.py
Last active September 4, 2022 15:07
Show Gist options
  • Select an option

  • Save lionelyoung/8cad668d4d30fa392842fa08d50d2bc6 to your computer and use it in GitHub Desktop.

Select an option

Save lionelyoung/8cad668d4d30fa392842fa08d50d2bc6 to your computer and use it in GitHub Desktop.

Revisions

  1. lionelyoung revised this gist Feb 9, 2020. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions http_server_auth.py
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Extended python -m http.serve with --username and --password parameters for
    # basic auth, based on https://gist.github.com/fxsjy/5465353

    # Usage: python -m http_server_auth -u USERNAME -p PASSWORD -d .
    from functools import partial
    from http.server import SimpleHTTPRequestHandler, test
    import base64
    @@ -14,7 +14,7 @@ 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)
    super().__init__(*args)

    def do_HEAD(self):
    self.send_response(200)
  2. @mauler mauler revised this gist Oct 31, 2019. No changes.
  3. @mauler mauler renamed this gist Oct 31, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  4. @mauler mauler revised this gist Oct 31, 2019. 1 changed file with 59 additions and 30 deletions.
    89 changes: 59 additions & 30 deletions SimpleAuthServer.py
    Original file line number Diff line number Diff line change
    @@ -1,49 +1,78 @@
    import BaseHTTPServer
    from SimpleHTTPServer import SimpleHTTPRequestHandler
    import sys
    # 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. """

    key = ""
    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)

    class AuthHandler(SimpleHTTPRequestHandler):
    ''' Main class to present webpages and authentication. '''
    def do_HEAD(self):
    print "send header"
    self.send_response(200)
    self.send_header('Content-type', 'text/html')
    self.send_header("Content-type", "text/html")
    self.end_headers()

    def do_AUTHHEAD(self):
    print "send header"
    self.send_response(401)
    self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
    self.send_header('Content-type', 'text/html')
    self.send_header("WWW-Authenticate", 'Basic realm="Test"')
    self.send_header("Content-type", "text/html")
    self.end_headers()

    def do_GET(self):
    global key
    ''' Present frontpage with user authentication. '''
    if self.headers.getheader('Authorization') == None:
    """ Present frontpage with user authentication. """
    if self.headers.get("Authorization") == None:
    self.do_AUTHHEAD()
    self.wfile.write('no auth header received')
    pass
    elif self.headers.getheader('Authorization') == 'Basic '+key:
    self.wfile.write(b"no auth header received")
    elif self.headers.get("Authorization") == "Basic " + self._auth:
    SimpleHTTPRequestHandler.do_GET(self)
    pass
    else:
    self.do_AUTHHEAD()
    self.wfile.write(self.headers.getheader('Authorization'))
    self.wfile.write('not authenticated')
    pass
    self.wfile.write(self.headers.get("Authorization").encode())
    self.wfile.write(b"not authenticated")

    def test(HandlerClass = AuthHandler,
    ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)

    if __name__ == "__main__":
    import argparse

    if __name__ == '__main__':
    if len(sys.argv)<3:
    print "usage SimpleAuthServer.py [port] [username:password]"
    sys.exit()
    key = base64.b64encode(sys.argv[2])
    test()
    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)
  5. @fxsjy fxsjy created this gist Apr 26, 2013.
    49 changes: 49 additions & 0 deletions SimpleAuthServer.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    import BaseHTTPServer
    from SimpleHTTPServer import SimpleHTTPRequestHandler
    import sys
    import base64

    key = ""

    class AuthHandler(SimpleHTTPRequestHandler):
    ''' Main class to present webpages and authentication. '''
    def do_HEAD(self):
    print "send header"
    self.send_response(200)
    self.send_header('Content-type', 'text/html')
    self.end_headers()

    def do_AUTHHEAD(self):
    print "send header"
    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):
    global key
    ''' Present frontpage with user authentication. '''
    if self.headers.getheader('Authorization') == None:
    self.do_AUTHHEAD()
    self.wfile.write('no auth header received')
    pass
    elif self.headers.getheader('Authorization') == 'Basic '+key:
    SimpleHTTPRequestHandler.do_GET(self)
    pass
    else:
    self.do_AUTHHEAD()
    self.wfile.write(self.headers.getheader('Authorization'))
    self.wfile.write('not authenticated')
    pass

    def test(HandlerClass = AuthHandler,
    ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)


    if __name__ == '__main__':
    if len(sys.argv)<3:
    print "usage SimpleAuthServer.py [port] [username:password]"
    sys.exit()
    key = base64.b64encode(sys.argv[2])
    test()