上期教程中我们完成了MQTT服务器的搭建,但是没有为连接设置用户名密码,这有一定的安全风险,本期来详细讲解一下如何为MQTT创建用户名密码。
1 创建用户
1.1 创建第一个用户
在终端输入下面的命令创建第一个用户(esp32_device):
# -c 表示创建新文件(首次用这个,以后添加用户不要再加 -c)
sudo mosquitto_passwd -c /etc/mosquitto/pwdfile esp32_device回车后会提示输入两次密码,密码不显示是正常的
1.2 创建其他用户
创建完第一个用户后,再添加其他用户时不需要再加 -c,否则会覆盖掉之前的用户,使用-b 参数可以直接把密码写在命令里:
# 添加第二个用户(不加 -c)
sudo mosquitto_passwd -b /etc/mosquitto/pwdfile 新用户名 新密码这里创建了livingroom_esp32和bedroom_esp32两个用户,他们的密码都是123
sudo mosquitto_passwd -b /etc/mosquitto/pwdfile livingroom_esp32 123
sudo mosquitto_passwd -b /etc/mosquitto/pwdfile bedroom_esp32 123所有被创建的用户都可以在/etc/mosquitto/pwdfile路径下找到
2 修改配置文件
sudo nano /etc/mosquitto/mosquitto.confpersistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
listener 1883 0.0.0.0
allow_anonymous false
password_file /etc/mosquitto/pwdfile很容易看出区别,就是将原来的认证方式由允许匿名访问true改为false,并添加了存储有用户名和密码的路径
3 重启Mosquitto
sudo systemctl restart mosquitto检查一下是否正常运行:
sudo systemctl status mosquitto看到绿色的 active (running) 就表示成功了,这样,我们就修改为密码认证的方式了。
4 总结
修改完配置文件重启后服务可能并没有成功启动,可能是文件权限问题(密码文件的所有者是 root,但 Mosquitto 服务运行在 mosquitto 用户下,没有权限读取这个文件),可以试试运行下面的指令修改文件权限:
sudo chown mosquitto:mosquitto /etc/mosquitto/pwdfile执行下面的命令验证文件权限:
ls -la /etc/mosquitto/pwdfile如果显示如下就可以了:
-rw------- 1 mosquitto mosquitto 126 Apr 9 11:24 /etc/mosquitto/pwdfile重启后查看状态应该就能看到绿色的 active (running) 了:
sudo systemctl restart mosquitto
sudo systemctl status mosquitto