emqx-auth-pgsql 它經過檢查每一個終端接入的 username 和 password 是否與用戶指定 的 PostgreSQL 數據庫中存儲的信息一致來實現對終端的訪問控制。其功能邏輯以下:sql
本文假設 PostgreSQL 已經安裝在您的機器上,而且您能夠鏈接到 PostgreSQL 服務器。數據庫
emqx-auth-pgsql 提供了 mqtt.sql 文件幫助用戶快速創建數據庫環境,mqtt.sql 將在 auth.pgsql.database 指定的數據庫下建立 mqtt_user 和 mqtt_acl 兩張表,併爲 mqtt_acl 添加如下默認規則:服務器
以上規則含義可參考: 《基於 MySQL 的 EMQ X Auth & ACL》。測試
1.Mac 環境安裝 mosquittoui
brew install mosquitto加密
2.導入 mqtt.sql 後,手動插入如下兩條數據3d
mqtt=# insert into mqtt_user (id, is_superuser, username, password, salt) values (1, false, 'test', 'password', 'salt'); mqtt=# insert into mqtt_acl (id, allow, ipaddr, username, clientid, access, topic) values (7, 0, NULL, 'test', NULL, 1, 'mytopic');cdn
3.修改配置文件blog
禁止匿名訪問:ip
.../etc/emqx.conf allow_anonymous = false 配置數據庫中密碼的加密方式爲 plain,既不加密:
.../etc/plugins/emqx_auth_pgsql.conf auth.pgsql.password_hash = plain 配置要訪問的數據庫以及用戶名密碼:
.../etc/plugins/emqx_auth_pgsql.conf auth.pgsql.username = root auth.pgsql.password = public auth.pgsql.database = mqtt
4.啓動 EMQ X 與 emqx-auth-pgsql
./_rel/emqx/bin/emqx start emqx 3.1 is started successfully! ./_rel/emqx/bin/emqx_ctl plugins load emqx_auth_pgsql
5.測試
a.使用正確的用戶名和密碼進行鏈接,並訂閱 "topic" 主題
$ mosquitto_sub -p 1883 -u test -P password -t 'topic' -d Client mosqsub|4119-zhouzibode sending CONNECT Client mosqsub|4119-zhouzibode received CONNACK Client mosqsub|4119-zhouzibode sending SUBSCRIBE (Mid: 1, Topic: topic, QoS: 0) Client mosqsub|4119-zh ouzibode received SUBACK Subscribed (mid: 1): 0 現象:鏈接並訂閱成功
b.使用錯誤的用戶名或密碼進行鏈接,並訂閱 "topic" 主題
$ mosquitto_sub -p 1883 -u bad_user -P password -t 'topic' -d Client mosqsub|4363-zhouzibode sending CONNECT Client mosqsub|4363-zhouzibode received CONNACK Connection Refused: not authorised. 現象:鏈接被拒絕
c.使用正確的用戶名和密碼進行鏈接,並訂閱 "#" 主題
$ mosquitto_sub -p 1883 -u test -P password -t '#' -d Client mosqsub|4392-zhouzibode sending CONNECT Client mosqsub|4392-zhouzibode received CONNACK Client mosqsub|4392-zhouzibode sending SUBSCRIBE (Mid: 1, Topic: #, QoS: 0) Client mosqsub|4392-zhouzibode received SUBACK Subscribed (mid: 1): 128
現象:鏈接成功,訂閱失敗,緣由碼128
d.使用正確的用戶名和密碼進行鏈接,並訂閱 "mytopic" 主題
$ mosquitto_sub -p 1883 -u test -P password -t 'mytopic' -d Client mosqsub|4428-zhouzibode sending CONNECT Client mosqsub|4428-zhouzibode received CONNACK Client mosqsub|4428-zhouzibode sending SUBSCRIBE (Mid: 1, Topic: mytopic, QoS: 0) Client mosqsub|4428-zhouzibode received SUBACK Subscribed (mid: 1): 128
現象:鏈接成功,訂閱失敗,緣由碼128