使用自签名证书在 Tornado 中进行相互认证

Mutual Authentication in Tornado with self signed certificates

通过 Tornado 文档,我似乎无法找到关于 两种方式的 SSL 身份验证。目前使用自签名证书的代码看起来像这样:

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()

您需要设置 ssl.SSLContextverify_mode:

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)

然后就可以使用self.request.get_ssl_certificate获取客户​​端的证书了。