Secure websocket server using autobahn and trollius (asyncio)

Websockets are a pretty useful way of passing information to and from clients.  But how do you make them secure?  I’m documenting how I’m figuring it out as I go.  Let’s get started.

First, let’s get a simple autobahn server and client up and running.  This is straight from the asyncio example on github.  Running it with python and python respectively.

To make things secure, first we need to create some keys and certificates.  I am creating a self-signed certificate and key for both the server and the test client:

Next we need to add a few lines to our server and client.  For the server add:

sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sslcontext.load_cert_chain(‘server.crt’, “server.key”)
and when we create the server, we will pass in the context.  Find the “loop.create_server” line and change it to:
coro = loop.create_server(factory, ‘’, 9000, ssl=sslcontext)
The client is almost identical:
sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sslcontext.load_cert_chain(‘client.crt’, “client.key”)
coro = loop.create_connection(factory, ‘’, 9000, ssl=sslcontext)
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.