Not able to connect to Azure IoT devices from a remote server, but can connect to them from my localhost.

Suraj Kamtam 0 Reputation points
2025-07-09T16:31:37.9633333+00:00

In my application I am sending data to the azure iot devices. When I ran the application in my localhost, it ran fine and sent the data. But when I installed the application on a server, the connection is being refused all the time. How to solve this? I ran a simple code to test the connection on the server. I have been getting the following error. I logged the entire process. Please help me in solving this issue. I have tried various solutions but nothing worked. There is nothing wrong with the connection string, the devices, the ports are allowed in the firewall, and the server clock is synchronized.

Error log:

Current server time: 2025-07-09 16:16:53.049008

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting run_op in pipeline thread

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Creating pipeline executor

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_http:Gateway Hostname not present. Setting Hostname to: EVDTHub.azure-devices.net

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_http:HTTPTransportStage(InitializePipelineOperation): got connection args

DEBUG:azure.iot.device.common.http_transport:creating a SSL context

DEBUG:azure.iot.device.common.pipeline.pipeline_ops_base:InitializePipelineOperation: completing without error

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting <azure.iot.device.common.evented_callback.EventedCallback object at 0x71fd15f9c050> in callback thread

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Creating callback executor

DEBUG:azure.iot.device.common.evented_callback:Callback completed with result None

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting run_op in pipeline thread

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_base:SasTokenStage: Scheduling automatic SAS Token renewal at epoch time: 1752081293

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_mqtt:Gateway Hostname not present. Setting Hostname to: EVDTHub.azure-devices.net

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_mqtt:MQTTTransportStage(InitializePipelineOperation): got connection args

DEBUG:azure.iot.device.common.mqtt_transport:creating mqtt client

INFO:azure.iot.device.common.mqtt_transport:Creating client for connecting using MQTT over TCP

DEBUG:azure.iot.device.common.mqtt_transport:creating a SSL context

DEBUG:azure.iot.device.common.mqtt_transport:configuring SSL context with default certs

DEBUG:azure.iot.device.common.mqtt_transport:Created MQTT protocol client, assigned callbacks

DEBUG:azure.iot.device.common.pipeline.pipeline_ops_base:InitializePipelineOperation: completing without error

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting <azure.iot.device.common.evented_callback.EventedCallback object at 0x71fd14ef2290> in callback thread

DEBUG:azure.iot.device.common.evented_callback:Callback completed with result None

SAS Token: SharedAccessSignature sr=EVDTHub.azure-devices.net%2Fdevices%2FEVSE-1%2Fmodules%2FEV-1&sig=oBD3WTI149Sai%2FrwJrjK0HxR1NETgSN4noZgLdix0wY%3D&se=1752081413

INFO:azure.iot.device.iothub.sync_clients:Connecting to Hub...

DEBUG:azure.iot.device.iothub.pipeline.mqtt_pipeline:Starting ConnectOperation on the pipeline

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting run_op in pipeline thread

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_base:ConnectionStateStage(ConnectOperation): State changes DISCONNECTED -> CONNECTING. Sending op down

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_mqtt:MQTTTransportStage(ConnectOperation): connecting

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_mqtt:MQTTTransportStage(ConnectOperation): Starting watchdog

DEBUG:azure.iot.device.common.mqtt_transport:connecting to mqtt broker

INFO:azure.iot.device.common.mqtt_transport:Connect using port 8883 (TCP)

DEBUG:paho:Sending CONNECT (u1, p1, wr0, wq0, wf0, c0, k60) client_id=b'EVSE-1/EV-1'

DEBUG:azure.iot.device.common.mqtt_transport:_mqtt_client.connect returned rc=0

DEBUG:paho:Received CONNACK (0, 5)

INFO:azure.iot.device.common.mqtt_transport:connected with result code: 5

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting _on_mqtt_connection_failure in pipeline thread

INFO:azure.iot.device.common.pipeline.pipeline_stages_mqtt:MQTTTransportStage: _on_mqtt_connection_failure called: Connection Refused: not authorised.

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_mqtt:MQTTTransportStage: failing connect op

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_mqtt:MQTTTransportStage(ConnectOperation): cancelling watchdog

INFO:azure.iot.device.common.mqtt_transport:disconnected with result code: 5

DEBUG:azure.iot.device.common.pipeline.pipeline_ops_base:ConnectOperation: completing with error Connection Refused: not authorised.

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_base:ConnectionStateStage(ConnectOperation): failed, state change ConnectionState.CONNECTING -> DISCONNECTED

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting on_complete in callback thread

INFO:azure.iot.device.common.evented_callback:Callback completed with error Connection Refused: not authorised.

INFO:azure.iot.device.common.evented_callback:NoneType: None

DEBUG:azure.iot.device.common.mqtt_transport: File "/usr/lib/python3.11/threading.py", line 1002, in _bootstrap

self._bootstrap_inner()

File "/usr/lib/python3.11/threading.py", line 1045, in _bootstrap_inner

self.run()

File "/usr/lib/python3.11/threading.py", line 982, in run

self._target(*self._args, **self._kwargs)

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/paho/mqtt/client.py", line 3591, in _thread_main

self.loop_forever(retry_first_connection=True)

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/paho/mqtt/client.py", line 1756, in loop_forever

rc = self._loop(timeout)

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/paho/mqtt/client.py", line 1164, in _loop

rc = self.loop_read()

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/paho/mqtt/client.py", line 1558, in loop_read

return self._loop_rc_handle(rc)

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/paho/mqtt/client.py", line 2350, in _loop_rc_handle

self._do_on_disconnect(rc, properties)

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/paho/mqtt/client.py", line 3475, in _do_on_disconnect

on_disconnect(self, self._userdata, rc)

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/azure/iot/device/common/mqtt_transport.py", line 208, in on_disconnect

logger.debug("".join(traceback.format_stack()))

INFO:azure.iot.device.common.mqtt_transport:Forcing paho disconnect to prevent it from automatically reconnecting

DEBUG:azure.iot.device.common.mqtt_transport:in paho thread. nulling _thread

DEBUG:azure.iot.device.common.mqtt_transport:Done forcing paho disconnect

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting _on_mqtt_disconnected in pipeline thread

Traceback (most recent call last):

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/azure/iot/device/iothub/sync_clients.py", line 36, in handle_result

INFO:azure.iot.device.common.pipeline.pipeline_stages_mqtt:MQTTTransportStage: _on_mqtt_disconnect called: The connection was refused.

return callback.wait_for_completion()

WARNING:azure.iot.device.common.pipeline.pipeline_stages_base:ConnectionStateStage: DisconnectEvent received while in unexpected state - ConnectionState.DISCONNECTED

       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/azure/iot/device/common/evented_callback.py", line 69, in wait_for_completion

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_base:ConnectionStateStage(DisconnectedEvent): State changes ConnectionState.DISCONNECTED -> DISCONNECTED. Unexpected disconnect in unexpected state

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_base:PipelineRootStage: DisconnectedEvent received. Calling on_disconnected_handler

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting _on_disconnected in callback thread

INFO:azure.iot.device.common.pipeline.pipeline_stages_mqtt:MQTTTransportStage: Unexpected disconnect (no pending connection op)

raise self.exception

INFO:azure.iot.device.iothub.abstract_clients:Connection State - Disconnected

azure.iot.device.common.transport_exceptions.UnauthorizedError: Connection Refused: not authorised.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File "/home/ev_sim/ev_car_sim/apps/core/azure_test.py", line 11, in <module>

DEBUG:azure.iot.device.common.pipeline.pipeline_stages_base:PipelineRootStage: BackgroundExceptionEvent received. Calling on_background_exception_handler

client.connect()

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/azure/iot/device/patch_documentation.py", line 146, in connect

INFO:azure.iot.device.iothub.abstract_clients:Cleared all pending method requests due to disconnect

return super(IoTHubModuleClient, self).connect()

       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/azure/iot/device/iothub/sync_clients.py", line 229, in connect

DEBUG:azure.iot.device.common.pipeline.pipeline_thread:Starting _on_background_exception in callback thread

handle_result(callback)

File "/home/ev_sim/ev_car_sim/new_venv/lib/python3.11/site-packages/azure/iot/device/iothub/sync_clients.py", line 44, in handle_result

WARNING:azure.iot.device.common.handle_exceptions:Exception caught in background thread. Unable to handle.

WARNING:azure.iot.device.common.handle_exceptions:['azure.iot.device.common.transport_exceptions.ConnectionDroppedError: Unexpected disconnection\n']

raise exceptions.CredentialError("Credentials invalid, could not connect") from e

azure.iot.device.exceptions.CredentialError: Credentials invalid, could not connect

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
{count} votes

2 answers

Sort by: Most helpful
  1. VSawhney 880 Reputation points Microsoft External Staff Moderator
    2025-07-10T05:51:06.77+00:00

    Hello Suraj Kamtam,

    The error you're encountering — Connection Refused: not authorised — when connecting to Azure IoT Hub from a remote server (but not from localhost) typically points to an authentication or environment-specific configuration issue.

    The logs show that:

    • The SAS token is being generated and used.
    • The MQTT connection is initiated successfully (rc=0).
    • But the broker returns CONNACK (0, 5) which means "Connection Refused: Not Authorized".

    This confirms that the issue is not network-related (since port 8883 is reachable), but rather authentication-related.

    You may follow these troubleshooting steps:

    1. Double-check the environment variables Ensure the connection string is being correctly loaded on the server. Sometimes, environment variables or config files are not set up the same way as on your local machine.
    2. Verify the connection string format Make sure the connection string includes the correct device ID and is not URL-encoded or malformed. It should look like:
         HostName=<your-hub>.azure-devices.net;DeviceId=<device-id>;SharedAccessKey=<key>
      
    3. Check for module vs. device client mismatch You're using IoTHubModuleClient, which is for IoT Edge modules. If you're connecting a regular device, use IoTHubDeviceClient instead.
    4. Validate SAS token generation If you're generating a SAS token manually or using a custom method, ensure the token is valid and not expired. The error suggests the token might be rejected by the IoT Hub.
    5. Check for IP restrictions or network policies Some Azure IoT Hubs may have IP filtering or private endpoint configurations. Make sure your server’s IP is allowed to connect.
    6. Try running a minimal test script Use a simple script with hardcoded connection string to isolate the issue:
         from azure.iot.device import IoTHubDeviceClient
         client = IoTHubDeviceClient.create_from_connection_string("<your-connection-string>")
         client.connect()
      
    7. Enable verbose logging You already have debug logs, which is great. You can also enable logging at the SDK level to capture more details:
         import logging
         logging.basicConfig(level=logging.DEBUG)
      

    If after all this the issue persists, try regenerating the device key in Azure IoT Hub and updating the connection string. Hope this helps!
    Thank you!

    0 comments No comments

  2. Sander van de Velde | MVP 36,941 Reputation points MVP Volunteer Moderator
    2025-07-10T14:21:53.66+00:00

    Hello @Suraj Kamtam

    welcome to this moderated Azure community forum.

    It seems you want to deploy a Python device app on another machine than your development device.

    The application works well on your development device, so I expect it will look a bit like this.

    The application does not need much, just an outbound connection to the IoT Hub so please check if the connection can be made:

    • Is your server connected to the internet?
    • Can you connect your development machine to the same network as the server? or vice-versa?
    • Does the network (firewall) support the protocol? Try to switch over to eg. MQTT over websockets if you plan to use MQTT. This just needs port 443 instead of the MQTT port.

    Also, an IoT Hub device client can only run on one location so close the one on the development machine if you use the same credentials.


    If the response helped, do "Accept Answer". If it doesn't work, please let us know the progress. All community members with similar issues will benefit by doing so. Your contribution is highly appreciated.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.