-
Notifications
You must be signed in to change notification settings - Fork 1
Home
Leo Chen edited this page Jul 25, 2021
·
3 revisions
You can use the following script instead of launching CGIHTTPServer from command line.
Usage:
cgi_auth.py [port] [username:password]
#!/usr/bin/env python2
import BaseHTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
import sys
import base64
key = ""
class AuthHandler(CGIHTTPRequestHandler):
''' 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:
CGIHTTPRequestHandler.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 cgi_auth.py [port] [username:password]"
sys.exit()
key = base64.b64encode(sys.argv[2])
test()