Search code examples
tornadoself-signedmutual-authentication

Mutual Authentication in Tornado with self signed certificates


Going through the Tornado docs, I can't seem to find a treatment about two way SSL authentication. Currently the codes looks something like this using self-signed certificates:

import tornado.ioloop
import tornado.web
import tornado.httpserver

class fooHandler(tornado.web.RequestHandler):
    def get(self):
      #Do Something

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/foo/", fooHandler),
    ])
    http_server = tornado.httpserver.HTTPServer(application, ssl_options={
            "certfile": "./cert.pem",
            "keyfile": "./key.pem",
        })
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Solution

  • You need to set the verify_mode of your ssl.SSLContext:

    ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_ctx.load_cert_chain("cert.pem", "key.pem")
    # If your certs are not self-signed, load your CA certificates here.
    #ssl_ctx.load_verify_locations("cacerts.pem")
    ssl_ctx.verify_mode = ssl.CERT_REQUIRED
    http_server = HTTPServer(application, ssl_options=ssl_ctx)
    

    Then you can use self.request.get_ssl_certificate to get the client's certificate.