环境信息
- EMQX 版本:5.0.1
- 操作系统及版本:Debian 11
- 其他
问题描述
按照官网 https://www.emqx.io/docs/zh/v5.0/security/authn/jwt.html#配置与使用
为 EMQX Broker 配置了 JWT
权限控制
根据文档描述,满足如下条件,应该可以正确连接
- 生成 JWT token 的 key 与 Broker 中配置的 key 一致 , 我这里都是默认的
emqxsecret
- 在
password
中填写 JWT token
但是接下来,无论通过
- MQTTX (GUI)
- Golang SDK ( paho.mqtt.golang)
都无法成功链接到 Broker
配置文件及日志
Broker 配置
#cat /var/lib/emqx/configs/cluster-override.conf
authentication {
algorithm = "hmac-based"
from = "password"
mechanism = "jwt"
secret = "emqxsecret"
"secret_base64_encoded" = false
use_jwks = false
verify_claims {}
』
MQTTX 配置
Golang SDK 代码
package main
import (
"fmt"
"os"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/spf13/pflag"
)
func main() {
var broker string
var topic string
var clientID string
var action string
var msg string
var passwd string
pflag.StringVarP(&broker, "broker", "b", "x.x.x.x:1883", "Address of broker, ip:port")
pflag.StringVarP(&topic, "topic", "t", "testtopic", "topic name")
pflag.StringVar(&clientID, "clientid", "someclient", "client id for mqtt")
pflag.StringVar(&action, "action", "", "action: pub or sub")
pflag.StringVar(&msg, "msg", "", "msg to be published")
pflag.StringVar(&passwd, "passwd", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImZvbyIsImV4cCI6MTY1OTM1MzYyNX0.FTkF3Y8vjf1QUyrSdgdne6_7bu0g-oGHehh8_ZGxn4g", "password for mqtt")
pflag.Parse()
if action != "pub" && action != "sub" {
fmt.Println("Invalid setting for --action, must be pub or sub")
return
}
opts := mqtt.NewClientOptions()
opts.AddBroker(broker)
opts.SetClientID(clientID)
if passwd != "" {
opts.SetPassword(passwd)
}
fmt.Println(opts)
if action == "pub" {
// publish a message
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
token := client.Publish(topic, 0, false, msg)
token.Wait()
//client.Disconnect(250)
//fmt.Println("Publisher Disconnected")
} else {
// subscribe a topic
choke := make(chan [2]string)
opts.SetDefaultPublishHandler(func(client mqtt.Client, msg mqtt.Message) {
choke <- [2]string{msg.Topic(), string(msg.Payload())}
})
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
if token := client.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
incoming := <-choke
fmt.Printf("TOpic: %s. MESSAGE: %S\n", incoming[0], incoming[1])
client.Disconnect(250)
fmt.Println("Subscriber Disconnectes")
}
}
运行报错
./mqtt --action pub --msg shaya
&{[tcp://x.x.x.x:1883] someclient eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImZvbyIsImV4cCI6MTY1OTM1MzYyNX0.FTkF3Y8vjf1QUyrSdgdne6_7bu0g-oGHehh8_ZGxn4g <nil> true true false [] 0 false 0 false <nil> 30 10s 30s 10m0s true 30s false <nil> <nil> <nil> 0x605be0 <nil> <nil> 0s 0 false map[] 0xc0000ae138 0 0xc0000b8300 <nil>}
panic: not Authorized
goroutine 1 [running]:
main.main()
/home/foo/workspace/go/mqtt-demo/cmd/mqtt/main.go:45 +0x99d