mosca icon indicating copy to clipboard operation
mosca copied to clipboard

Connect mqtt client from browser using web sockets with HTTPS

Open helpme1 opened this issue 10 years ago • 5 comments

I would like to run a mqtt client on a web browser using web sockets with HTTPS. With HTTP, I have no problem. Here is the code on the web browser when using HTTP.

<script>
      //Node.js MQTT server start command : 
      //mosca --very-verbose --credentials ./credentials.json --http-port 3000 --http-bundle --http-static ./ | pino
      var client  = mqtt.connect( 'ws://127.0.0.1:3000', {username:'test_user', password:'test_password'} );
      client.subscribe("mqtt/test");

      client.on("message", function(topic, payload) {
        alert([topic, payload].join(": "));
        client.end();
      });

      client.publish("mqtt/test", "testing hello world!");
</script> 

This is how I start the stand-alone mosca broker to use HTTPS on websockets. mosca --very-verbose --key ./tls-key.pem --cert ./tls-cert.pem --credentials ./credentials.json --https-port 3000 --https-bundle --https-static ./ | pino

How should I change my mqtt client code on the browser to connect to the Mosca broker on websockets via HTTPS?

helpme1 avatar Oct 14 '16 03:10 helpme1

I think you should just avoid putting the url in the mqtt.connect(), if the html is served by mosca. Otherwise, you need to use the wss protocol, as it's a secure websocket.

mcollina avatar Oct 14 '16 06:10 mcollina

I tried with wss but I got the error "WebSocket connection to 'wss://127.0.0.1:3000/' failed: WebSocket opening handshake was canceled"

helpme1 avatar Oct 14 '16 06:10 helpme1

The browser will usually prompt the user that a particular page is unsafe when visiting a HTTPS website if the certificate is self-signed. The MQTT connection shouldn't just fail without prompting. Could it be because the browser don't prompt when it's initiated from javascript? Does it mean there is no way to use MQTTS from a web browser?

helpme1 avatar Oct 17 '16 01:10 helpme1

@helpme1 That will not happen for websocket connections. Serve your full website through that insecure HTTPS certificate and it should work. Or use a signed certificate, or install your certificate manually on your browser.

mcollina avatar Oct 17 '16 08:10 mcollina

Is there any guide to configure Mosca for secure WebSocket.

ompurwar avatar Oct 05 '18 11:10 ompurwar