moscajs / mosca

MQTT broker as a module
mosca.io
3.2k stars 509 forks source link

Connect mqtt client from browser using web sockets with HTTPS #557

Closed helpme1 closed 7 years ago

helpme1 commented 7 years ago

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?

mcollina commented 7 years ago

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.

helpme1 commented 7 years ago

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 commented 7 years ago

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?

mcollina commented 7 years ago

@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.

ompurwar commented 5 years ago

Is there any guide to configure Mosca for secure WebSocket.