Skip to content

Instantly share code, notes, and snippets.

@jamesgregson
Created October 16, 2019 04:01
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 jamesgregson/a8975b259b6190f0c146ed09bc4d0dd1 to your computer and use it in GitHub Desktop.
Save jamesgregson/a8975b259b6190f0c146ed09bc4d0dd1 to your computer and use it in GitHub Desktop.
Python3 http.server with basic authorization
import time
import base64
from http.server import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
if 'Authorization' in self.headers:
vals = self.headers['Authorization'].split()[1]
userpass = base64.b64decode(vals).decode('utf-8')
content = bytes('''
<html>
<body>
<h1>Authorization header sent</h1>
You sent: {}<br>
Header was: {}<br>
Should be: {}
</body>
</html>'''.format(userpass,vals,self.server.key), 'utf-8' )
self.send_response(200)
self.send_header('Content-type','text/html')
self.send_header('Content-length',len(content) )
self.end_headers()
self.wfile.write( content )
else:
content = bytes('<html><body><h1>401 - Not Authorized</h1></body></html>','utf-8')
self.send_response(401)
self.send_header('WWW-Authenticate','Basic realm="User Visible Realm, charset="UTF-8"')
self.send_header('Content-type','text/html')
self.send_header('Content-length', len(content) )
self.end_headers()
self.wfile.write( content )
if __name__ == '__main__':
HOST_NAME = '127.0.0.1'
PORT_NUMBER = 9000
server_class = HTTPServer
httpd = server_class((HOST_NAME,PORT_NUMBER), MyHandler)
httpd.key = base64.b64encode('james:hello'.encode('ascii')).decode('utf-8')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment