Skip to content

Commit

Permalink
Merge pull request #1113 from jeremycline/doc-twisted-external-auth
Browse files Browse the repository at this point in the history
Add an example for Twisted authentication with x509 certs
  • Loading branch information
lukebakken committed Dec 19, 2018
2 parents 96875f0 + 50d3c2f commit 5d8ffb6
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion docs/examples/tls_mutual_authentication.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ TLS parameters example

This example demonstrates a TLS session with RabbitMQ using mutual authentication (server and client authentication). It was tested against RabbitMQ 3.7.4, using Python 3.6.5 and Pika 1.0.0b1.

See https://www.rabbitmq.com/ssl.html for certificate generation and RabbitMQ TLS configuration.
See `the RabbitMQ TLS/SSL documentation <https://www.rabbitmq.com/ssl.html>`_ for certificate generation and RabbitMQ TLS configuration. Please note that the `RabbitMQ TLS (x509 certificate) authentication mechanism <https://github.com/rabbitmq/rabbitmq-auth-mechanism-ssl>`_ must be enabled for these examples to work.

tls_example.py::

Expand Down Expand Up @@ -42,3 +42,46 @@ rabbitmq.config::
management.listener.ssl_opts.cacertfile = PIKA_DIR/testdata/certs/ca_certificate.pem
management.listener.ssl_opts.certfile = PIKA_DIR/testdata/certs/server_certificate.pem
management.listener.ssl_opts.keyfile = PIKA_DIR/testdata/certs/server_key.pem


To perform mutual authentication with a Twisted connection::

from pika import ConnectionParameters
from pika.adapters import twisted_connection
from pika.credentials import ExternalCredentials

from twisted.internet import defer, protocol, ssl, reactor

@defer.inlineCallbacks
def publish(connection):
channel = yield connection.channel()
yield channel.basic_publish(
exchange='amq.topic',
routing_key='hello.world',
body='Hello World!',
)
print("published")

# Load the CA certificate to validate the server's identity
with open("PIKA_DIR/testdata/certs/ca_certificate.pem") as fd:
ca_cert = ssl.Certificate.loadPEM(fd.read())

# Load the client certificate and key to authenticate with the server
with open("PIKA_DIR/testdata/certs/client_key.pem") as fd:
client_key = fd.read()
with open("PIKA_DIR/testdata/certs/client_certificate.pem"") as fd:
client_cert = fd.read()
client_keypair = ssl.PrivateCertificate.loadPEM(client_key + client_cert)

context_factory = ssl.optionsForClientTLS(
"localhost",
trustRoot=ca_cert,
clientCertificate=client_keypair,
)
params = ConnectionParameters(credentials=ExternalCredentials())
cc = protocol.ClientCreator(
reactor, twisted_connection.TwistedProtocolConnection, params)
deferred = cc.connectSSL("localhost", 5671, context_factory)
deferred.addCallback(lambda protocol: protocol.ready)
deferred.addCallback(publish)
reactor.run()

0 comments on commit 5d8ffb6

Please sign in to comment.