【问题标题】:Using websockets secure (wss) in angular ngx-mqtt to connect to mosquitto broker fails to connect在角度 ngx-mqtt 中使用 websockets secure (wss) 连接到 mosquitto 代理无法连接
【发布时间】:2022-11-14 12:30:54
【问题描述】:

我有一个 Angular 12 Web 应用程序,它通过端口上的 websockets (ws) 订阅代理上的主题,从 mosquitto 代理检索 mqtt 数据9001,这有效。

我现在已经通过following this guide. 创建我自己的自签名证书和密钥来加密从发布到代理的设备传入的 mqtt 数据这工作正常并且在端口上工作8883.

我还尝试加密连接到我的代理的 Angular Web 应用程序之间的通信以检索数据。到目前为止,在我的连接设置中,我已将协议启用为 websockets 安全(wss)而不是标准的 websockets(ws)

export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = 
{
  hostname: '<BROKER IP>', 
  port: 9001,
  protocol: 'wss', 
  username: '<BROKER USERNAME>', 
  password: '<BROKER PASSWORD>'
};

我已将 mosquitto.conf 文件调整为以下内容,thanks to this question,其中答案表明您需要为每个侦听器指定证书和密钥,在我的情况下,websockets 为 9001,加密 mqtt 为 8883:

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d

allow_anonymous false

password_file /etc/mosquitto/pwfile

#TLS CONFIG
listener 8883
cafile /etc/mosquitto/certs/mqtt_ca.crt
certfile /etc/mosquitto/certs/mqtt_srv.crt
keyfile /etc/mosquitto/certs/mqtt_srv.key
tls_version tlsv1.2

listener 9001
protocol websockets
cafile /etc/mosquitto/certs/mqtt_ca.crt
certfile /etc/mosquitto/certs/mqtt_srv.crt
keyfile /etc/mosquitto/certs/mqtt_srv.key

但是,当我查看我的浏览器(这是勇敢的)时,我在控制台中收到以下错误:

如果我使用普通的 websocket(ws)在Angular webapp中连接到代理它工作正常,但显然它没有加密。

我确保在我的代理上,我允许来自操作系统和路由器防火墙上端口 9001 和 8883 的传入连接。

我不知道为什么会这样,任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 页面是否通过 http 或 https 加载(如果是,它使用与代理相同的主机/证书)?您是否已将自签名证书导入浏览器证书存储区?
  • 嗨,目前我的 Web 应用程序只是在本地运行以进行测试,而且当它部署到 Web 服务器时,它暂时只使用 http。我不知道浏览器证书商店,这会是浏览器设置下的一个选项吗?是否需要将我的 mqtt_ca.crt 导入其中?还是 mqtt_srv.crt?谢谢。

标签: angular websocket mqtt tls1.2 mosquitto


【解决方案1】:

通过 JavaScript(例如 Javascript MQTT 客户端)访问资源时,浏览器不会像加载网页时那样提示您手动接受自签名证书。

你有几个选择:

  1. 确保托管 MQTT 客户端的页面也使用与代理相同的证书通过 HTTPS 加载。这将使浏览器提示您接受与自签名证书连接的风险,然后该证书应延续到 MQTT WebSocket 连接。

  2. 将自签名证书导入浏览器证书存储区并将其标记为受信任。这只是一个真正的开发选项,因为您需要为所有将访问该站点的浏览器执行此操作。您导入的证书取决于您创建证书的方式,但如果您有 CA 证书,则导入该证书。

【讨论】:

    最近更新 更多