[英]node.js mqtt client using TLS
I am trying to implement a node.js mqtt client with TLS using the package below; 我正在尝试使用以下软件包使用TLS实现node.js mqtt客户端;
https://www.npmjs.com/package/mqtt#client https://www.npmjs.com/package/mqtt#client
The code for running mqtt client without TLS is as follows; 在不使用TLS的情况下运行mqtt客户端的代码如下;
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
How should the above code be modified to use TLS on the mqtt client? 应该如何修改以上代码以在mqtt客户端上使用TLS?
The mosca MQTT broker was run as a stand-alone using the command below; mosca MQTT代理是使用以下命令独立运行的;
mosca --key ./tls-key.pem --cert ./tls-cert.pem --http-port 3000 --http-bundle --http-static ./ | pino
Should be enough to change the protocol
part of the URL to mqtts://
应该足以将URL的
protocol
部分更改为mqtts://
mqtts://test.mosquitto.org
. mqtts://test.mosquitto.org
。
Self-signed certificates 自签名证书
You can pass the following option to the connect
function when using self-signed certificates (for testing purposes only): 使用自签名证书时,可以将以下选项传递给
connect
函数(仅用于测试目的):
mqtt.connect('mqtts://test.mosquitto.org', {
rejectUnauthorized: false
});
You need to provide the mqtt.connect()
function with an options object which includes the CA certificate to use to verify the connection. 您需要为
mqtt.connect()
函数提供一个选项对象,该对象包括用于验证连接的CA证书。
The options object needs to include a ca
key that points to the certificate used to sign the brokers certificate. options对象需要包含一个
ca
密钥,该密钥指向用于对代理证书进行签名的证书。 As it looks like your using a self signed certificate this will be the same one used by the broker. 看起来您使用的是自签名证书,这与代理使用的证书相同。
The ca
key is described here 此处描述了
ca
密钥
Or you can allow any certificate with the rejectUnauthorized
key as mentioned in @notion's answer. 或者,您可以使用
rejectUnauthorized
的答案中提到的带有rejectUnauthorized
密钥的任何证书。 But that makes it impossible to detect if somebody is impersonating your broker 但这使得无法检测是否有人在冒充您的经纪人
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.