在java上试图使用org.eclipse.paho.client.mqttv3连接连接本地部署的emq,emqx服务端的认证配置如下
- 内置数据库Password-Based,
- 密码加密方式为plain,
- 加盐方式为disable
使用"emqx_test"作为用户名,使用"emqx_test_password"作为密码。测试连接时,总是连接失败,提示如下异常
org.eclipse.paho.client.mqttv3.MqttSecurityException: 错误的用户名或密码
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28)
at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:1053)
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:151)
at java.base/java.lang.Thread.run(Thread.java:840)
我在mqttx的mqtt协议调试软件上确定了"emqx_test"和"emqx_test_password"的用户名密码时没有问题的
截图:
相关java设置代码
var brokerUrl="tcp://127.0.0.1:1883";
mqttClient = new MqttAsyncClient(brokerUrl, "test");
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setUserName("emqx_test");
connOpts.setPassword("emqx_test_password".toCharArray());
connOpts.setServerURIs(new String[] { brokerUrl });
connOpts.setCleanSession(true);
// 设置回调函数
mqttClient.connect(connOpts, connStatus);
连接失败回调代码,连接总是响应REASON_CODE_FAILED_AUTHENTICATION的状态码
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable e) {
// System.out.println("Failed to connect to the broker: " +
// exception.getMessage());
if (e instanceof MqttException) {
MqttException mqttEx = (MqttException) e;
int reasonCode = mqttEx.getReasonCode();
if (reasonCode == MqttException.REASON_CODE_CLIENT_TIMEOUT) {
log.error("mqtt连接失败,等待超时");
} else if (reasonCode == MqttException.REASON_CODE_FAILED_AUTHENTICATION) {
log.error("连接失败,认证无效:",e);
} else {
System.out.println("Other connection failure reason: " + reasonCode);
}
} else {
log.error("连接失败", e);
}
}
请问问题出在哪里?
我把emqx上的内置数据库认证功能关了,java的mqtt连接就能成功了。然后打开emqx网站,进入客户端那一页面查看连接的客户端,在用户名那一列发现java的mqtt客户端缺少用户名,是MqttConnectOptions配置缺失了什么东西吗?
emqx测试的版本是emqx-5.3.2-windows-amd64
自己解决了,是要把"mqttClient.connect(connOpts, connStatus);"这段代码,改成如下的代码,才会启用用户名认证进行连接
mqttClient.connect(connOpts, null,connStatus)
效果反馈截图