我的mqtt协议和emqttd开源项目个人理解(14) - 使用redis插件来实现访问控制

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 我的mqtt协议和emqttd开源项目个人理解(14) - 使用redis插件来实现访问控制

一、工作环境准备


准备好redis server,http://blog.csdn.net/libaineu2004/article/details/76267836


erlang redis客户端使用开源项目,https://github.com/wooga/eredis


erlang连接池,https://github.com/emqtt/ecpool


emq使用的是v2.3.5版本,https://github.com/emqtt/emq-relx


我们以插件emq_auth_redis来实现,路径是/home/firecat/Prj/emq2.0/emq-relx-2.3.5/deps/emq_auth_redis


/home/firecat/Prj/emq2.0/emq-relx-2.3.5/data/loaded_plugins设置自启动插件


emq_recon. 
emq_modules. 
emq_retainer. 
emq_dashboard. 
emq_auth_redis.




二、redis数据准备


对照/home/firecat/Prj/emq2.0/emq-relx-2.3.5/deps/emq_auth_redis/README.md说明文档,往redis数据库写入username和password:


格式

HSET mqtt_user:<username> password "password"


命令

[root@localhost src]# ./redis-cli
127.0.0.1:6379> HSET mqtt_user:firecat password "123456"
(integer) 1
127.0.0.1:6379> HSET mqtt_user:lqh password "pass123"
(integer) 1
127.0.0.1:6379> HSET mqtt_user:firecatGTerm password "he2345v11t11"
(integer) 1
127.0.0.1:6379> hgetall mqtt_user
(empty list or set)
127.0.0.1:6379> HMGET mqtt_user:lqh password
1) "pass123"
127.0.0.1:6379> hgetall mqtt_user:lqh
1) "password"
2) "pass123"




源文件/home/firecat/Prj/emq2.0/emq-relx-2.3.5/deps/emqttd/src/emqttd_access_control.erl会启用校验


%% @doc Authenticate MQTT Client.
-spec(auth(Client :: mqtt_client(), Password :: password()) -> ok | {ok, boolean()} | {error, term()}).
auth(Client, Password) when is_record(Client, mqtt_client) ->
    auth(Client, Password, lookup_mods(auth)).
auth(_Client, _Password, []) ->
    case emqttd:env(allow_anonymous, false) of
        true  -> ok;
        false -> {error, "No auth module to check!"}
    end;
auth(Client, Password, [{Mod, State, _Seq} | Mods]) ->
    case catch Mod:check(Client, Password, State) of
        ok              -> ok;
        {ok, IsSuper}   -> {ok, IsSuper};
        ignore          -> auth(Client, Password, Mods);
        {error, Reason} -> {error, Reason};
        {'EXIT', Error} -> {error, Error}
    end.


源文件emq_auth_redis.erl,有校验的实施过程


check(Client, Password, #state{auth_cmd  = AuthCmd,

                              super_cmd = SuperCmd,

                              hash_type = HashType}) ->

   Result = case emq_auth_redis_cli:q(AuthCmd, Client) of


源文件emq_auth_redis_cli.erl,有redis的查询命令实现方法


%% Redis Query.

-spec(q(string(), mqtt_client()) -> {ok, undefined | binary() | list()} | {error, atom() | binary()}).

q(CmdStr, Client) ->

   io:format("1 CmdStr is: ~s  ~n", [CmdStr]),

   Cmd = string:tokens(replvar(CmdStr, Client), " "),

   io:format("2 Cms is: ~s  ~n", [Cmd]),

   ecpool:with_client(?APP, fun(C) -> eredis:q(C, Cmd) end).

ereids的使用案例,https://github.com/wooga/eredis


{ok, C} = eredis:start_link().

{ok, <<"OK">>} = eredis:q(C, ["SET", "foo", "bar"]).

{ok, <<"bar">>} = eredis:q(C, ["GET", "foo"]).

KeyValuePairs = ["key1", "value1", "key2", "value2", "key3", "value3"].

{ok, <<"OK">>} = eredis:q(C, ["MSET" | KeyValuePairs]).

{ok, Values} = eredis:q(C, ["MGET" | ["key1", "key2", "key3"]]).


string:tokens的用法可以参考erlang官方文档,http://erlang.org/doc/man/string.html


tokens(String, SeparatorList) -> Tokens

Types

String = SeparatorList = string()

Tokens = [Token :: nonempty_string()]

Returns a list of tokens in String, separated by the characters in SeparatorList.

Example:

> tokens("abc defxxghix jkl", "x ").

["abc", "def", "ghi", "jkl"]




三、除了emq_auth_redis_cli.erl上诉的查询方法,我们自己也可以实现其他查询方法:


-export([connect/1, q/2, q2/2]).
%% Redis Query.firecat add.
-spec(q2(string(), binary()) -> {ok, undefined | binary() | list()} | {error, atom() | binary()}).
q2(CmdStr, ClientId) ->
    io:format("3 CmdStr is: ~s  ~n", [CmdStr]),
    Cmd = string:tokens(replvar(CmdStr, "%c", ClientId), " "),
    io:format("4 Cms is: ~s  ~n", [Cmd]),
    ecpool:with_client(?APP, fun(C) -> eredis:q(C, Cmd) end).

这样,我在其他任意的erlang mod,都可以调用该方法,例如**.erl:


%%%% redis test
redis_test(ClientId) ->
   Result = case emq_auth_redis_cli:q2("HMGET mqtt_clientid:%c user group type", ClientId) of
                {ok, [undefined|_]} ->
                    io:format("clientid ignore: undefined  ~n"), %%firecat
                    {error, undefined};
                {ok, [User, Group, Type]} -> %%[undefined, undefined, undefined]
                    io:format("clientid is: ~s ~s ~s ~n", [User, Group, Type]),
                    ok;
                {error, Reason} ->
                    io:format("clientid error is: ~s  ~n", [Reason]),
                    {error, Reason}
             end,
   case Result of
             ok -> ok; %%firecat
             Error -> ok
             end.


四、redis插件除了可以检验username和password,还可以校验clientid的合法性。需要手动新增源文件emq_clientid_redis.erl。完整的源码请访问:


https://download.csdn.net/download/libaineu2004/10289890


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1月前
|
监控 网络性能优化 网络安全
【MODBUS】Modbus主站为边缘设备通过MQTT协议上云
【MODBUS】Modbus主站为边缘设备通过MQTT协议上云
34 1
|
2月前
|
安全 网络安全 数据安全/隐私保护
|
2月前
|
物联网 Linux 开发工具
MQTT协议接入问题之连接失败如何解决
MQTT接入是指将设备或应用通过MQTT协议接入到消息服务器,以实现数据的发布和订阅;本合集着眼于MQTT接入的流程、配置指导以及常见接入问题的解决方法,帮助用户实现稳定可靠的消息交换。
134 2
|
2月前
|
JSON 物联网 开发工具
MQTT协议问题之如何搭建物联网空调的服务器
MQTT协议是一个轻量级的消息传输协议,设计用于物联网(IoT)环境中设备间的通信;本合集将详细阐述MQTT协议的基本原理、特性以及各种实际应用场景,供用户学习和参考。
78 1
|
2月前
|
JSON 网络协议 物联网
MQTT协议问题之消息类型分类如何解决
MQTT协议是一个轻量级的消息传输协议,设计用于物联网(IoT)环境中设备间的通信;本合集将详细阐述MQTT协议的基本原理、特性以及各种实际应用场景,供用户学习和参考。
49 3
|
1月前
|
消息中间件 存储 监控
RabbitMQ:分布式系统中的高效消息队列
RabbitMQ:分布式系统中的高效消息队列
|
4月前
|
消息中间件 NoSQL 数据库
一文讲透消息队列RocketMQ实现消费幂等
这篇文章,我们聊聊消息队列中非常重要的最佳实践之一:消费幂等。
一文讲透消息队列RocketMQ实现消费幂等
|
1月前
|
消息中间件 Java
springboot整合消息队列——RabbitMQ
springboot整合消息队列——RabbitMQ
74 0
|
3月前
|
消息中间件 JSON Java
RabbitMQ消息队列
RabbitMQ消息队列
46 0
|
3月前
|
消息中间件
RabbitMQ 实现消息队列延迟
RabbitMQ 实现消息队列延迟
121 0