2. MQTT客户端连接认证
任务目标
配置MQTT Broker的用户名密码认证,使客户端必须提供合法凭据才能建立连接,拒绝匿名访问与错误密码。
环境依赖
使用Mosquitto作为Broker(支持v2.0+),客户端使用Python paho-mqtt库。安装命令:pip install paho-mqtt。Broker需本地已安装,以下配置与验证均在本地执行。
实现步骤
1. Broker认证配置(mosquitto.conf)
# 关闭匿名连接
allow_anonymous false
# 指定密码文件路径
password_file /etc/mosquitto/passwd
# 监听端口(默认1883)
listener 1883
生成密码文件(需交互输入两次密码):
mosquitto_passwd -c /etc/mosquitto/passwd iot_user
如需追加更多用户,去掉-c参数重复执行。
2. 客户端认证连接代码(client_auth.py)
import paho.mqtt.client as mqtt
BROKER = "127.0.0.1"
PORT = 1883
USERNAME = "iot_user"
PASSWORD = "secure123"
def on_connect(client, userdata, flags, rc, properties=None):
if rc == 0:
print("连接成功")
elif rc == 5:
print("认证失败:用户名或密码错误")
else:
print(f"连接失败,返回码:{rc}")
client.disconnect()
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.username_pw_set(USERNAME, PASSWORD)
client.on_connect = on_connect
client.connect(BROKER, PORT, 60)
client.loop_forever()
运行与验证
启动Broker:
mosquitto -c /etc/mosquitto/mosquitto.conf
验证路径:
- 正确凭据:运行
python client_auth.py,输出连接成功,Broker日志显示New client connected。 - 错误密码:将代码中
PASSWORD改为错误值,运行后输出认证失败,Broker日志显示Bad username or password。 - 匿名测试:注释掉
username_pw_set行,运行后输出连接失败,返回码:5,Broker拒绝连接。
通过条件:上述三种场景行为与预期一致,即Broker仅接受配置文件中存在的用户名且密码正确,否则拒绝连接。
常见问题
- 若提示
password_file路径无权限,将passwd文件归属改为运行mosquitto的用户,或使用sudo启动。 - Broker默认配置可能包含
allow_anonymous true,需确认自定义配置覆盖默认值(使用-c指定配置文件时不会加载/etc/mosquitto/mosquitto.conf以外的默认配置)。