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

如何配置Mosquitto MQTT Broker拒绝证书CN与客户端ID不匹配的连接?

让Mosquitto拦截客户端ID与证书CN不一致的连接

要实现设备连接时必须保证客户端ID和证书CN一致,不一致就拒绝,主要有两种实用方法:

方法一:用自定义脚本做连接校验

Mosquitto支持通过外部脚本完成连接认证,你可以写个简单脚本,在设备发起连接时对比客户端ID和证书CN:

  1. 修改Mosquitto配置
    在mosquitto.conf中添加以下配置:

    # 禁用匿名连接
    allow_anonymous false
    # 启用外部认证插件(以auth-plug插件为例,需提前安装)
    auth_plugin /usr/lib/mosquitto/auth-plug.so
    # 指定校验脚本的路径
    auth_opt_script /opt/mosquitto/check-clientid-cn.sh
    # 关闭认证缓存,确保每次连接都执行校验
    auth_opt_cacheseconds 0
    
  2. 编写校验脚本
    脚本可读取Mosquitto传递的环境变量:$clientid是客户端发送的ID,$tls_cn是证书中的CN字段值,直接对比即可:

    #!/bin/bash
    if [ "$clientid" != "$tls_cn" ]; then
        exit 1  # 返回非0值表示拒绝连接
    fi
    exit 0  # 返回0值表示允许连接
    

    给脚本添加执行权限:chmod +x /opt/mosquitto/check-clientid-cn.sh

  3. 重启Mosquitto服务

    systemctl restart mosquitto
    

方法二:用内置ACL规则匹配

如果不需要复杂逻辑,直接利用Mosquitto的ACL变量即可:%c代表客户端ID,%x代表证书CN:

  1. 配置Mosquitto指定ACL文件
    在mosquitto.conf中添加:

    allow_anonymous false
    acl_file /etc/mosquitto/acl.conf
    
  2. 编写ACL规则
    在acl.conf中添加规则,仅允许客户端ID与证书CN一致的设备通过校验:

    # 仅允许客户端ID等于证书CN的设备访问所有主题
    topic readwrite #
    pattern readwrite %x/%c
    

    原理是%x/%c只有当两者完全相等时才会匹配成功,否则设备无法获得任何主题权限,连接会被拒绝。

测试验证

用mosquitto_sub工具测试两种场景:

# 合法场景:证书CN为device01,客户端ID也设为device01,可正常连接
mosquitto_sub -h 你的Broker地址 -t test -i device01 --cafile ca.crt --cert device01.crt --key device01.key

# 非法场景:使用device01的证书,但客户端ID设为device02,连接会被拒绝
mosquitto_sub -h 你的Broker地址 -t test -i device02 --cafile ca.crt --cert device01.crt --key device01.key

内容的提问来源于stack exchange,提问作者vignesh ramesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:21:25