You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 09:11:54