Stack Overflow Asked by govtham on November 5, 2020
I am trying to use Microsoft Azure IOT Hub(MQTT) to connect my java client device to IOT Hub(without SDK). I created device and SAS with TTL as required. I am using paho client to connect to IoT Hub.I am getting below error. SAS token i created from IoT Hub Tools with 5 hours of expiry time.
Not authorized to connect (5)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28)
at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:1040)
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:151)
at java.lang.Thread.run(Unknown Source)
Below is the code i am trying
String deviceId = "mqqdirectdevice1";
String brokerUri = "ssl://xxxxx:8883";
String clientId = deviceId;
System.out.println( "Connecting to " + brokerUri +" as "+clientId);
MqttAsyncClient client = null;
try {
String sasToken="SharedAccessSignature sr=xxxxxxx.azure-devices.net%2Fdevices%2Fmqqdirectdevice1&sig=iJ3jacTNMdyyhIrQueBN5X6uEqURYCKfa5Z63ePKDRs%3D&se=1600335545";
client = new MqttAsyncClient( brokerUri, clientId,new MemoryPersistence());
if ( client != null ) {
MqttConnectOptions options = new MqttConnectOptions();
client.setCallback( new AzureCallback() );
options.setUserName("xxxxxx.net/mqqdirectdevice1?api-version=2018-06-30");
options.setPassword(sasToken.toCharArray());
// options.setPassword(sasToken.toCharArray());
options.setKeepAliveInterval(230);
options.setCleanSession(false);
options.setMqttVersion(4);
IMqttToken token=client.connect( options );
token.waitForCompletion(60 * 1000);
System.out.println("Sent MQTT CONNECT packet was acknowledged");
if ( client.isConnected() ) {
System.out.println( "Success!" );
} else {
System.out.println( "Could not connect to Azure IoT hub, timed-out" );
}
}
} catch ( MqttException) {
//client.getDebug().dumpBaseDebug();
e.printStackTrace();
} finally {
if ( client != null ) {
try {
client.disconnect();
} catch ( MqttException ignore ) {}
}
}
In your example, you use the following username:
xxxxxx.net/mqqdirectdevice1?api-version=2018-06-30
The format is slightly different, you are currently missing a forward slash before the question mark. The correct format is:
xxxxxx.net/mqqdirectdevice1/?api-version=2018-06-30
I tested it, and the MQTT connection can't be made with the username in an incorrect format.
Answered by Matthijs van der Veer on November 5, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP