使用X.509证书通过npm mqtt连接Azure IoT Hub遇未授权问题
问题
尝试直接使用npm的mqtt库,通过X.509证书认证向Azure IoT Hub发送遥测消息,但连接时提示未授权。使用Azure Node.js SDK时设备连接正常且能发送消息,相关代码及错误信息如下:
代码示例
const mqtt = require("mqtt"); const fs = require('fs'); let options = { cert: fs.readFileSync("device-cert.pem", "utf-8").toString(), key: fs.readFileSync("device-cert.key", "utf-8").toString(), passphrase: '1234', clientId: "device-003", username: "ih-iot-sample-001.azure-devices.net/device-003/?api-version=2021-04-12", } let client = mqtt.connect( "mqtts://ih-iot-sample-001.azure-devices.net:8883", options ); client.on("connect", function () { console.log("connected"); }); client.on("error", (err) => { console.log(err); process.exit(0) });
错误信息
Connection refused: Not authorized
排查与解决
针对X.509认证下mqtt库连接Azure IoT Hub的授权问题,可从以下几个方向调整:
修正证书读取方式:证书和私钥属于二进制文件,不要用
utf-8编码读取,改为直接读取原始二进制数据,避免编码转换破坏证书内容:cert: fs.readFileSync("device-cert.pem"), key: fs.readFileSync("device-cert.key"),调整Username参数格式:Azure IoT Hub的MQTT连接不需要在Username中携带
api-version参数,正确格式应为{IoT Hub名称}/{设备ID}:username: "ih-iot-sample-001.azure-devices.net/device-003",验证证书链完整性:确保设备证书由Azure IoT Hub信任的CA签发;若使用自签名证书,需将根CA证书上传至IoT Hub并启用证书验证,同时检查设备证书是否包含完整的证书链(含中间CA)。
启用调试日志排查:在连接选项中添加
debug: true,查看更详细的连接交互日志,定位具体授权失败原因:let options = { // 原有参数 debug: true }
内容的提问来源于stack exchange,提问作者Badhusha
相关产品推荐
相关产品推荐

