TheDev88
TheDev88

Reputation: 335

How to properly connect with authentication in HiveMQ?

I'm trying to connect a client to a server with simple authentication using HiveMQ. On HiveMQ Client I created a client and used the connectWith() to specify that I want to connect with simple authentication. When I inputted a username and password I get a MqttClientStateException which I left below. Am I supposed to store/configure a username and password manually on the server as I just inputted a username and password like the tutorial here:

https://hivemq.github.io/hivemq-mqtt-client/docs/mqtt_operations/connect.html#authenticationauthorization .

Code:

Mqtt5BlockingClient publisher = Mqtt5Client.builder()
    .identifier(UUID.randomUUID().toString()) // the unique identifier of the MQTT client. The ID is randomly generated between 
    .serverHost("localhost")  // the host name or IP address of the MQTT server. Kept it localhost for testing. localhost is default if not specified.
    .serverPort(1883)  // specifies the port of the server
    .addConnectedListener(context -> ClientConnectionRetreiver.printConnected("Publisher1"))         // prints a string that the client is connected
    .addDisconnectedListener(context -> ClientConnectionRetreiver.printDisconnected("Publisher1"))  // prints a string that the client is disconnected
    .buildBlocking();  // creates the client builder                
    publisher.connectWith() // connects the client
        .simpleAuth()
            .username("Username")
            .password("Password".getBytes())
            .applySimpleAuth();

Exception:

Exception in thread "SubThread1" com.hivemq.client.mqtt.exceptions.MqttClientStateException: MQTT client is not connected.
at com.hivemq.client.internal.mqtt.MqttBlockingClient.subscribe(MqttBlockingClient.java:101)
at com.hivemq.client.internal.mqtt.message.subscribe.MqttSubscribeBuilder$Send.send(MqttSubscribeBuilder.java:184)
at com.main.SubThread.run(SubThread.java:83)
at java.base/java.lang.Thread.run(Thread.java:834)

Upvotes: 1

Views: 1959

Answers (1)

SgtSilvio
SgtSilvio

Reputation: 496

You forgot to send the connect message

publisher.connectWith()
        .simpleAuth()
            .username("Username")
            .password("Password".getBytes())
            .applySimpleAuth()
        .send();

If you really want to authenticate the client, you have to configure the server. With HiveMQ you could use the File Role based Access Control Extension (https://www.hivemq.com/extension/file-rbac-extension/) for a simple authentication.

Upvotes: 4

Related Questions