Search code examples
mqttpahoamazon-mq

How to connect to Amazon MQ Broker with Mosquitto MQTT Client


I created a single instance broker with Amazon MQ, and were able to subscribe to the broker with just username and password using Eclipse Paho MQTT Client.

The code:

//sample endpoint from Amazon MQ
final String WIRE_LEVEL_ENDPOINT = "ssl://b-1234a5b6-78cd-901e-2fgh-3i45j6k178l9-1.mq.us-east-2.amazonaws.com:8883";
final String ACTIVE_MQ_USERNAME = "user";
final String ACTIVE_MQ_PASSWORD = "password";

// Specify the topic name and the message text.
final String topic = "whatever";
final String text = "Hello from Amazon MQ!";

// Create the MQTT client and specify the connection options.
final String clientId = "abc123";
final MqttClient client = new MqttClient(WIRE_LEVEL_ENDPOINT, clientId);
final MqttConnectOptions connOpts = new MqttConnectOptions();

// Pass the username and password.
connOpts.setUserName(ACTIVE_MQ_USERNAME);
connOpts.setPassword(ACTIVE_MQ_PASSWORD.toCharArray());

// Create a session and subscribe to a topic filter.
client.connect(connOpts);
client.setCallback(this);
client.subscribe(topic);

// Create a message.
final MqttMessage message = new MqttMessage(text.getBytes());

// Publish the message to a topic.
client.publish(topic, message);
System.out.println("Published message.");

// Wait for the message to be received.
Thread.sleep(3000L);

// Clean up the connection.
client.disconnect();

Running the code above shows that I am able to subscribe to the topic and also receive the message that I've sent.

However, doing the same with mosquitto_sub client, it gives me protocol error:

mosquitto_sub -h host -p 8883 -u user -P password -t whatever -i abc123

error:

Error: A network protocol error occurred when communicating with the broker.

And I searched on how to make connection to MQTT Broker with SSL. I found out that I need to set a certificate for the client.

enter image description here

But how come in java it worked without any certificate set???


Solution

  • Because to enable SSL support with mosquitto_sub you have to pass either --cafile or --capath. Without them the app will not even try to create a secure connection.

    It works in java because it has access to the list of public CA certs to check the brokers cert against. mosquitto_sub doesn't have that list so you need to pass it a cert to validate against.