Stomp connection using JWT token in Python

16 Views Asked by At

We have a cli written in python (using typer) and we want to add consuming websocket over stomp to it so the cli can connect to the RabbitMQ and consume the messages. I have to mention that there is an Nginx + Oauth2proxy sitting in front of our RabbitMQ and we have an entry in our Nginx for websocket over STOMP.

We have this feature in our GUI and the way that we do it is to use the JWT token instead of the username and password: wss://:JWT_TOKEN@URL/[PATH] and everything works.

In python I found the stomp library but I cannot make it work, below is my code and I tried different things but I got all types of errors, you can see some of the things that I tried as I commented them out:

import ssl
import stomp

class MyListener(stomp.ConnectionListener):
    def on_error(self, headers, message):
        print('Received an error "%s"' % message)

    def on_message(self, headers, message):
        print('Received a message "%s"' % message)

@stomp_app.command("listen")
def stomp_listen(
    path: str = typer.Option(
        ...,
        help="The STOMP endpoint PATH",
    ),
):
    """
    Examples: \n
        cli.py stomp listen --path [PATH] \n
        cli.py stomp listen --path /exchange/egress_exchange/sys_newproj_sim1 \n
    """
    url_without_https = URL.replace("https://", "")
    # endpoint = "wss://:"+jwt_token+"@"+url_without_https+"/ws"
    endpoint = "wss://"+url_without_https+"/ws"

    # Create an SSL context
    ssl_context = ssl.create_default_context()
    # conn = stomp.Connection([(endpoint, 443)]) 
    # conn.set_ssl(for_hosts=[(endpoint, 443)])
    conn = stomp.Connection([endpoint])
    conn.set_ssl(for_hosts=[endpoint])
    conn.set_listener('', MyListener())

    conn.connect(headers={'Authorization': 'Bearer ' + jwt_token}, wait=True)
    # conn.connect(username="",passcode=jwt_token,headers={'Authorization': 'Bearer ' + jwt_token}, wait=True)
    # conn.connect(username="",passcode=jwt_token, wait=True)
    # conn.connect(wait=True)
    conn.subscribe(destination=path, id=1, ack='auto')

    while True:
        pass

    conn.disconnect()

Can someone please help me how to connect to the STOMP in python?

0

There are 0 best solutions below