EMQX 登入認證,通過外部自建HTTP服務控制

劍匣破發表於2020-10-15

EMQX 登入認證,通過外部自建HTTP服務控制

官方教程

https://docs.emqx.net/broker/latest/cn/advanced/auth-http.html

在這裡插入圖片描述

啟動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

相關文章