上篇用TLS/SSL保证EMQ的网络传输安全讲了使用自签ca加密MQTT传输数据,如果mqtt用在web端,如何使用ssl、tsl加密?
1、web客户端
// 引入mqtt.min.js // 将在全局初始化一个 mqtt 变量 //console.log(mqtt); // 连接选项 const options = { connectTimeout: 4000, // 超时时间 // 认证信息 username: 'xiaoming', password: '123456', }; // ws是普通通讯,端口8083;wss是加密通讯,必须用域名连接,端口是8084 // const client = mqtt.connect('ws://192.168.0.43:8083/mqtt', options); const client = mqtt.connect('wss://www.test.com:8084/mqtt', options); // client. client.on('connect', (error) => { console.log('链接成功:', error) }); client.on('reconnect', (error) => { console.log('正在重连:', error) }); client.on('error', (error) => { console.log('连接失败:', error) }); // 订阅列表 client.subscribe('pub', { qos: 2 }); // 监听接收消息事件 client.on('message', (topic, message) => { // console.log('收到来自', topic, '的消息', message.toString()); });
2、EMQX服务端修改配置文件./emqx/etc/emqx.conf
## See: listener.ssl.$name.keyfile ## ## Value: File listener.wss.external.keyfile = etc/certs/MyEMQ1.key ## listener.wss.external.keyfile = etc/certs/emqx.key ## Path to a file containing the user certificate. ## ## See: listener.ssl.$name.certfile ## ## Value: File listener.wss.external.certfile = etc/certs/MyEMQ1.pem ## listener.wss.external.certfile = etc/certs/emqx.pem ## Path to the file containing PEM-encoded CA certificates. ## ## See: listener.ssl.$name.cacert ## ## Value: File listener.wss.external.cacertfile = etc/certs/MyRootCA.pem ## listener.wss.external.cacertfile = etc/certs/my_root_ca.pem
3、注意:把之前生成的ca根证书安装到本地计算机和浏览器上,重启浏览器即可使用ssl加密连接web客户端和EMQX服务器