mosquitto(mqtt) 认证 登陆(使用redis)

来源:互联网 发布:c语言所有水仙花数程序 编辑:程序博客网 时间:2024/06/14 03:38

物联网 qq 群:651219170

先通过 配置文件讲解认证的基本知识。后面在用 redis 认证插件做认证。

认证主在配置文件

# =================================================================# Security# =================================================================### 用户名密码认证allow_anonymous允许匿名password_file密码文件acl_file访问控制列表

配置用户名密码登陆

1.关掉匿名登陆
allow_anonymous false
2.配置用户名密码文件
password_file /usr/local/etc/mosquitto/pwfile
3.配置使用的权限文件
/usr/local/etc/mosquitto/aclfile
4.添加用户,这里添加两个
添加并创建文件
mosquitto_passwd -c /usr/local/etc/mosquitto/pwfile admin
添加用户
mosquitto_passwd /usr/local/etc/mosquitto/pwfile yuhaiyang

添加权限

#yuhaiyanguser yuhaiyangtopic  read control/##adminuser admintopic write #

使用 redis 做认证服务器。

下载插件。

https://github.com/jpmens/mosquitto-auth-plug/releases/
插件依赖 hiredis, openssl

安装 hiredis 客户端。

https://github.com/redis/hiredis/releases
make -j8
make install

安装 openssl

yum install openssl

编译插件。

进入mosquitto-auth-plug目录下
cp config.mk.in config.mk

编辑 config.mk 指定开启 redis , mosquitto 源码目录,openssl 目录 (这两个app安装到默认路径也可以不指定)。
BACKEND_REDIS ?= yes
其他的为 no。

创建一个插件目录。方便在 mosquitto中配置插件路径。

mkdir -p /usr/local/lib/mosquitto/plugin/
cp auth-plug.so /usr/local/lib/mosquitto/plugin

修改 mosquitto 开启redis 认证插件

修改mosquitto 的配置文件。
匿名登陆最好关掉。

allow_anonymous falseauth_plugin /usr/local/lib/mosquitto/plugin/auth-plug.soauth_opt_backends redisauth_opt_redis_host 192.168.25.162auth_opt_redis_port 6379auth_opt_redis_userquery GET %sauth_opt_redis_aclquery GET %s-%s

介绍:

auth_opt_redis_userquery GET %s
auth_opt_redis_aclquery GET %s-%s
In auth_opt_redis_userquery the parameter is the username, whereas in auth_opt_redis_aclquery, the first parameter is the username and the second is the topic. When using ACLS topic must be an exact match - wildcards are not supported.
翻译:
通过 redis 查找用户 get 用户名。获取密码与设备上报的密码(加密之后)进行匹配。注意 redis 中存的密码要是 PBKDF2 加密的密文。
redis 查询某个用户对某个主题的权限的时候 get 用户名-主题名 获取值。值为 1 对主题有读权限。值为 2 对主题有写权限。

在插件目录下生成用户名密码。
./np -p admin
生成的密码 set 到 redis

set admin PBKDF2$sha256$901$lzMxwbgXSoPWfG3U$J/UVQWp39U8AQWpaOZhO/Rf6hlqVogm0

创建权限 1 读权限 2读写权限
set admin-control/a 2
好了现在可以使用 mqtt 客户端来测试了。

备注

You never store actual passwords in the backend databases. Only the PBKDF2 strings of the passwords.
When you are starting mosquitto_sub and mosquitto_pub you need to use original passwords (and not PBKDF2 strings).
PBKDF2 strings are not reversible – that is, for the same password you are not guaranteed to get the same PBKDF2 string every time. They change. Which means, from PBKDF2 string you cannot get back your original password – so you have to remember your passwords (and not rely upon the database to get them back).

原创粉丝点击