前言:基於Mosquitto服務器已經搭建成功,大部分都是采用默認的是允許匿名用戶登錄模式,正式上線的系統需要進行用戶認證。
1.用戶參數說明
Mosquitto服務器的配置文件為/etc/mosquitto/mosquitto.conf,關於用戶認證的方式和讀取的配置都在這個文件中進行配置。
allow_anonymous允許匿名
password_file密碼文件
acl_file訪問控制列表
# 不允許匿名
allow_anonymous false
# 配置用戶密碼文件
password_file /etc/mosquitto/pwfile
# 配置topic和用戶
acl_file /etc/mosquitto/acl
2.添加用戶信息
添加用戶'admin'
#mosquitto_passwd -c /etc/mosquitto/pwfile admin
3.添加Topic和用戶的關系
#cat acl
找到你要的topic ---‘a/b’
#topic a/b
在下面添加
user admin topic write mtopic/#
找到#This affects all clients
添加
user admin topic read mtopic/#
4.用戶認證測試
重啟Mosquitto
通過Ctrl+C關閉mosquitto,然后通過下面命令啟動Mosquitto
# mosquitto-c /etc/mosquitto/mosquitto.conf
(訂閱端)客戶端啟動:
#mosquitto_sub -h 192.168.1.100 -t mtopic -u admin -P 123456
(發布者)客戶端啟動:
#mosquitto_pub -h 192.168.1.100 -t mtopic -u admin -P 123456 -m "test"