Skip to content

Instantly share code, notes, and snippets.

@vaaas
Forked from fxsjy/SimpleAuthServer.py
Last active April 12, 2022 07:04
Show Gist options
  • Save vaaas/11d7b6835a9470a76cf65fa8d851795a to your computer and use it in GitHub Desktop.
Save vaaas/11d7b6835a9470a76cf65fa8d851795a to your computer and use it in GitHub Desktop.
simple-auth-http-server: simple http server with basic authentication (works with python3!)
#!/usr/bin/env python3
import http.server
from http.server 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):
''' Present frontpage with user authentication. '''
global key
print(self.headers['Authorization'], key)
if self.headers['Authorization'] == None:
self.do_AUTHHEAD()
self.wfile.write('no auth header received')
pass
elif self.headers['Authorization'] == 'Basic '+key:
SimpleHTTPRequestHandler.do_GET(self)
pass
else:
self.do_AUTHHEAD()
self.wfile.write(bytes('not authenticated', encoding='utf-8'))
pass
def test(HandlerClass = AuthHandler, ServerClass = http.server.HTTPServer):
http.server.test(HandlerClass, ServerClass)
if __name__ == '__main__':
if len(sys.argv) < 3:
print('usage SimpleAuthServer.py [port] [username:password]')
sys.exit()
key = str(base64.b64encode(bytes(sys.argv[2], encoding='utf-8')), encoding='utf-8')
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment