Skip to content

Instantly share code, notes, and snippets.

@yous
Created December 5, 2016 10:49
Show Gist options
  • Save yous/14eb595c1d203f9ab321b8b29eb631b4 to your computer and use it in GitHub Desktop.
Save yous/14eb595c1d203f9ab321b8b29eb631b4 to your computer and use it in GitHub Desktop.
Multithreaded SimpleHTTPServer with basic auth
import os
import base64
import SocketServer
import BaseHTTPServer
import SimpleHTTPServer
class AuthHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
''' Main class to present webpages and authentication. '''
def do_AUTHHEAD(self):
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm=\"Auth\"')
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
global keys
''' Present frontpage with user authentication. '''
if self.headers.getheader('Authorization') == None:
self.do_AUTHHEAD()
self.wfile.write('No auth header received')
else:
for key in keys:
if self.headers.getheader('Authorization') == 'Basic ' + key:
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
return
else:
self.do_AUTHHEAD()
self.wfile.write(self.headers.getheader('Authorization'))
self.wfile.write('Not authenticated')
class ThreadingSimpleServer(SocketServer.ThreadingMixIn,
BaseHTTPServer.HTTPServer):
pass
import sys
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
keys = map(base64.b64encode, ['USERNAME:PASSWORD'])
os.chdir('files')
server = ThreadingSimpleServer(('', port), AuthHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
print('Finished')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment