Search code examples
javascriptwebsocketmqttmosquittopaho

How to use Secured Web Sockets with mosquitto and JS?


I have a frontend in JS connecting to a MQTT server (mosquitto) with the help of the Paho JavaScript Client. This works fine, I can publish and listen to topics.

I now would like to promote the Web Sockets connection to a secured one.

To this, I added to my /etc/mosquitto/mosquitto.conf the entries for certfile and keyfile:

pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
listener 1883
listener 1884
protocol websockets
# above is the working, non-wss configuration
certfile /etc/mosquitto/wildcard.crt
keyfile /etc/mosquitto/wildcard.key

Provided that this is the right configuration, how can I create a client in JS which would take into account the secure connection? For the existing one, I have

client = new Paho.MQTT.Client("10.10.10.10", 1884, Math.random().toString(16).substring(7))

and do not see any other configuration to be passed here?


Solution

  • From the docs

    You have several options:

    1. the host when declaring a new client can be a URI rather than just a ip/hostname

      client = new Paho.MQTT.Client("wss://10.10.10.10:1884", Math.random().toString(16).substring(7));
      
    2. You can use the useSSL flag in the client.connect(options) options object.

      client.connect({
        useSSL: true
       });