Created
December 5, 2016 10:49
-
-
Save yous/14eb595c1d203f9ab321b8b29eb631b4 to your computer and use it in GitHub Desktop.
Multithreaded SimpleHTTPServer with basic auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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