SCote SCote - 1 year ago 241
Java Question

Connect to Azure IoT Hub with Java Paho

We have started a PoC to connect some of our existing code the Azure IoT Hub via MQTT to test Azure’s support for standard protocols and tools. We are using the Paho client but are getting a CONNACK with a return code of 5 – Not Authorized.

We followed the instructions on how to setup an IoT Hub and created one using the F1 (free) scale tier. We then followed another Azure document and downloaded Device Explorer, created a device and generated a SAS token. We then plugged everything into Paho:

public static void main( String[] args ) {
String deviceId = "device-fcbd127a";
String sasToken = "SharedAccessSignature‌​Zg%3d&se=1468067737";
String brokerUri = "ssl://";
String clientId = deviceId;
System.out.println( "Connecting to " + brokerUri +" as "+clientId);

MqttAsyncClient client = null;
try {
client = new MqttAsyncClient( brokerUri, clientId );
if ( client != null ) {
MqttConnectOptions options = new MqttConnectOptions();
client.setCallback( new AzureCallback() );
options.setUserName( "" );
options.setPassword( sasToken.toCharArray() );
IMqttToken token = client.connect( options );
token.waitForCompletion( 5000 );
if ( client.isConnected() ) {
System.out.println( "Success!" );
} else {
System.out.println( "Could not connect to Azure IoT hub, timed-out" );
} catch ( MqttException e ) {
} finally {
if ( client != null ) {
try {
} catch ( MqttException ignore ) {}

We have confirmed with Wireshark that a SSL connection is made to Azure and that the CONNECT packet is sent. We then see the CONNACK with a return code of 5 being sent to Paho and Azure dropping the connection soon thereafter. We then looked into “Shared Access Policies” and tried different settings. There is nothing in the audit logs and we have “verbose” turned on for everything.

Has anyone connected Paho (or other third-party Java client) to the Azure IoT Hub?

Where do we find any diagnostic information so we can troubleshoot this ourselves?

On a side note, we shelved this (MQTT) approach and tried to connect via the ReST services and receive an even more ambiguous “500-Internal Server Error“ as a response. This makes us think there is a more fundamental access issue here. Does the F1 scale hub only support the Microsoft SDK? Are there some hidden access control settings we are missing? Is the format of the names strict, not allowing certain characters or case?

Answer Source

Apparently we had issues with the Device Explorer utility. Instead of generating a SAS Token with an expiry of 365 days, it generated a token good for only 365 seconds.

Note the se=1468067737 in the SAS token, it evaluates to an expiration of Jul 09 08:35:37 EDT 2016, well past our test execution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download