Connect mqtt client from browser using web sockets with HTTPS
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?
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.
I tried with wss but I got the error "WebSocket connection to 'wss://127.0.0.1:3000/' failed: WebSocket opening handshake was canceled"
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 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.
Is there any guide to configure Mosca for secure WebSocket.