EMQ X 入门教程 基础篇①——设备登录认证,通过外部自建HTTP服务控制

648 阅读1分钟

一、官方教程

docs.emqx.net/broker/late…

在这里插入图片描述

二、启动emqx_auth_http插件

在这里插入图片描述

三、修改emqx_auth_http.conf配置文件

emqx\etc\plugins\emqx_auth_http.conf 我的服务器是8080的端口,所以我就改了一个端口

##--------------------------------------------------------------------
## Authentication request.

## HTTP URL API path for authentication request
##
## Value: URL
##
## Examples: http://127.0.0.1:8991/mqtt/auth, https://[::1]:8991/mqtt/auth
auth.http.auth_req = http://127.0.0.1:8080/mqtt/auth

## Value: post | get | put
auth.http.auth_req.method = post

## It only works when method=post
## Value: json | x-www-form-urlencoded
auth.http.auth_req.content_type = x-www-form-urlencoded

## Variables:
##  - %u: username
##  - %c: clientid
##  - %a: ipaddress
##  - %r: protocol
##  - %P: password
##  - %p: sockport of server accepted
##  - %C: common name of client TLS cert
##  - %d: subject of client TLS cert
##
## Value: Params
auth.http.auth_req.params = clientid=%c,username=%u,password=%P

四、编写Http Api接口

在controller里面添加代码

    @ApiOperation("MQTT 登录认证")
    @PostMapping(value="/auth")
    public AjaxResult auth(@RequestParam String clientid, @RequestParam String username, @RequestParam String password) {
        logger.info("MQTT auth, clientid="+clientid+", username="+username+", password="+password);
        //do something
        return AjaxResult.success(200);
    }

五、Security配置

在SecurityConfig里面添加安全访问的限制,否则会访问不到

{
    "msg": "请求访问:/mqtt/auth,认证失败,无法访问系统资源",
    "code": 401
}

添加如下代码,有就可以了

.antMatchers("/mqtt/**").hasIpAddress("127.0.0.1") 
{
    "msg": "操作成功",
    "code": 200,
    "data": 200
}

六、MQTTBox测试

在MQTTBox上新建一个MQTT客户端,连接到我们本地的EMQX,则在我Java服务器上会打印一条log

11:53:54.045 [http-nio-8080-exec-1] INFO  c.r.m.c.MqttController - [auth,45] - MQTT auth, clientid=18b9abb0-e45e-4d2e-bb9e-f619cf49ab6e1602734033938, username=1111, password=1111

在这里插入图片描述