Created
March 10, 2017 13:32
-
-
Save miron0xff/b860d6f0cd39f3e8a5d4eeab29ef83d2 to your computer and use it in GitHub Desktop.
TLS Mutual Auth
This file contains 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
import os | |
import ssl | |
import http.server | |
import socketserver | |
HOST = 'localhost' | |
PORT = 8001 | |
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) | |
CERT_DIR = os.path.join(PROJECT_ROOT, 'certificates') | |
ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2) | |
ctx.verify_mode = ssl.CERT_REQUIRED | |
ctx.load_verify_locations(os.path.join(CERT_DIR, 'CA.crt')) | |
ctx.load_cert_chain( | |
certfile=os.path.join(CERT_DIR, 'webserver.crt'), | |
keyfile=os.path.join(CERT_DIR, 'webserver.key') | |
) | |
class RequestHandler(http.server.BaseHTTPRequestHandler): | |
def do_GET(self): | |
self.send_response(200) | |
self.send_header('Content-Type', 'text/html') | |
self.end_headers() | |
client_cert = self.connection.getpeercert() | |
subject = dict([x[0] for x in client_cert.get('subject')]) | |
self.wfile.write( | |
bytes('Hello, {}'.format(subject.get('commonName')), 'utf8') | |
) | |
return | |
if __name__ == '__main__': | |
socketserver.TCPServer.allow_reuse_address = True | |
httpd = socketserver.TCPServer((HOST, PORT), RequestHandler) | |
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True) | |
print('Serving on {}:{}'.format(HOST, PORT)) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment