Last active
April 7, 2019 10:02
-
-
Save aerobless/aa6e3d74842da19f25c2f588991f0c36 to your computer and use it in GitHub Desktop.
Simple HTTPS Basic Auth server in python
This file contains hidden or 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
# generate certificates for 10years with the following command: | |
# openssl req -new -x509 -keyout key.pem -out server.pem -days 3000 -nodes | |
# Startup with the following command: | |
# python3 server.py | |
import http.server | |
import ssl | |
import subprocess | |
import base64 | |
from http import HTTPStatus | |
class Handler(http.server.SimpleHTTPRequestHandler): | |
def do_HEAD(self, authenticated): | |
if authenticated: | |
self.send_response(200) | |
else: | |
self.send_response(401) | |
self.send_header('WWW-Authenticate','Basic realm=\"Secure Share\"') | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
def do_GET(self): | |
if self.headers.get('Authorization') == 'Basic '+key.decode('utf-8'): | |
self.do_HEAD(True) | |
self.wfile.write(bytes('Authorized! Sending new plant data!', 'utf-8')) | |
# Execute bash command | |
subprocess.Popen("plantgateway", stdout=subprocess.PIPE) | |
pass | |
elif self.headers.get('Authorization') == None: | |
self.do_HEAD(False) | |
self.wfile.write(bytes('Unauthorized! No credentials provided!', 'utf-8')) | |
pass | |
else: | |
self.do_HEAD(False) | |
self.wfile.write(bytes('Unauthorized! Bad credentials provided!', 'utf-8')) | |
pass | |
# Username and password for basic authentication | |
credentials = '{0}:{1}'.format("username", "password") | |
server_address = ('', 8000) | |
key = base64.b64encode(bytes(credentials, 'utf-8')) | |
httpd = http.server.HTTPServer(server_address, Handler) | |
httpd.socket = ssl.wrap_socket(httpd.socket, | |
server_side=True, | |
certfile="server.pem", | |
keyfile="key.pem", | |
ssl_version=ssl.PROTOCOL_TLSv1) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment