mosquito / aio-pika

AMQP 0.9 client designed for asyncio and humans.
https://aio-pika.readthedocs.org/
Apache License 2.0
1.25k stars 189 forks source link

SSL Connection example #246

Open JRafiei opened 5 years ago

JRafiei commented 5 years ago

Hi. Could you please provide some examples regarding ssl connection to the rabbitmq server? Specially in cases that there is no client certificate.

mosquito commented 5 years ago

Just use amqps://guest:guest@localhost/. When server has self-signed certificate, just add cafile parameter. e.g. amqps://guest:guest@localhost/?cafile=/home/user/.ssl/ca.pem

andvikt commented 2 years ago

cafile does not work.

import asyncio
import aio_pika

async def main() -> None:
    connection = await aio_pika.connect_robust(
        "amqps://some:some@11.11.11.11/?"
        "cafile=ssl/res/ca-cert.pem&"
        "keyfile=ssl/res/client-key.pem&"
        "certfile=ssl/res/client-cert.pem",
    )

    async with connection:
        channel = await connection.channel()

if __name__ == "__main__":
    asyncio.run(main())

Throws error: ConnectionError: [Errno 1] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1129)

So the only option is to set no_verify_ssl=1 which is insecure at all.

So maybe I am doing something wrong?

wangxin688 commented 11 months ago

see example below:

import asyncio
import aio_pika
import ssl

async def main() -> None:
    context = ssl.create_default_context(cafile=f"{PROJECT_DIR}/certs/ca_certificate.pem")
    context.check_hostname = False
    context.verify_mode = ssl.CERT_REQUIRED
    context.load_cert_chain(
            certfile=f"{PROJECT_DIR}/certs/client_certificate.pem",
            keyfile=f"{PROJECT_DIR}/certs/client_key.pem",
        )
    connection = await aio_pika.connect_robust(
        url="amqps://some:some@11.11.11.11/?"
        ssl=True, ssl_context=context
    )

    async with connection:
        channel = await connection.channel()

if __name__ == "__main__":
    asyncio.run(main())