Skip to content

Instantly share code, notes, and snippets.

@7enderhead
Forked from fxsjy/SimpleAuthServer.py
Last active May 4, 2019 17:44
Show Gist options
  • Save 7enderhead/a7614b6b5100e9a951b78a9eb437d265 to your computer and use it in GitHub Desktop.
Save 7enderhead/a7614b6b5100e9a951b78a9eb437d265 to your computer and use it in GitHub Desktop.
SimpleAuthServer: A SimpleHTTPServer with authentication
# Python3 compatible
import http.server
from http.server import SimpleHTTPRequestHandler
import sys
import base64
key = ""
class AuthHandler(SimpleHTTPRequestHandler):
''' Main class to present webpages and authentication. '''
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):
global key
''' Present frontpage with user authentication. '''
auth = self.headers.get('Authorization')
if auth == None:
self.do_AUTHHEAD()
self.wfile.write(b'no auth header received')
elif auth == 'Basic '+ key.decode('utf8'):
SimpleHTTPRequestHandler.do_GET(self)
else:
self.do_AUTHHEAD()
self.wfile.write(bytes(auth, 'utf8'))
self.wfile.write(b'not authenticated')
def test(HandlerClass = AuthHandler,
ServerClass = http.server.HTTPServer):
http.server.test(HandlerClass, ServerClass)
if __name__ == '__main__':
if len(sys.argv)<3:
print("usage SimpleAuthServer.py [port] [username:password]")
sys.exit()
key = base64.b64encode(bytes(sys.argv[2], 'utf8'))
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment