Skip to content

Instantly share code, notes, and snippets.

@wonjohnchoi
Forked from fxsjy/SimpleAuthServer.py
Last active August 26, 2015 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonjohnchoi/1cd3271458fb50611b6f to your computer and use it in GitHub Desktop.
Save wonjohnchoi/1cd3271458fb50611b6f to your computer and use it in GitHub Desktop.
SimpleAuthServer: A SimpleHTTPServer with authentication
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:
print 'authorized'
SimpleHTTPRequestHandler.do_GET(self)
pass
else:
self.do_AUTHHEAD()
self.wfile.write('not authenticated')
pass
if __name__ == '__main__':
if len(sys.argv) != 3:
print 'usage SimpleAuthServer.py [port] [username:password]'
else:
port = int(sys.argv[1])
key = base64.b64encode(sys.argv[2])
print 'listening on localhost:%d with key %s' %(port, key)
server = BaseHTTPServer.HTTPServer(('localhost', port), AuthHandler)
print 'Starting server, use <Ctrl-C> to stop'
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment