@ChrisRickard-4531 Welcome to Microsoft Q&A forum!
I have been trying to develop some simple code to connect to Azure IoT Hub via MQTT. I have been periodically successful in connecting but after a period of time, I begin to receive a "connection refused: not authorized" error.
Could you please confirm which SDK are you using?
The MQTT port (8883) is blocked in many corporate and educational networking environments. If you can't open port 8883 in your firewall, we recommend using MQTT over Web Sockets. MQTT over Web Sockets communicates over port 443, which is almost always open in networking environments. To learn how to specify the MQTT and MQTT over Web Sockets protocols when using the Azure IoT SDKs, see Using the device SDKs.
What is the Default keep-alive timeout you have set?
By default, the token lifespan is 60 minutes for all SDKs; however, it can be changed by developers in some of the SDKs. The following table summarizes the token lifespan, token renewal, and token renewal behavior for each of the SDKs: Please see Default keep-alive timeout and MQTT device disconnect behavior with Azure IoT SDKs for more details.
This error can also occurs because, for MQTT, some SDKs rely on IoT Hub to issue the disconnect when the SAS token expires to know when to refresh it. So,
- The SAS token expires
- IoT Hub notices the expiration, and disconnects the device with 401003 IoTHubUnauthorized
- The device completes the disconnection with 404104 DeviceConnectionClosedRemotely
- The IoT SDK generates a new SAS token
- The device reconnects with IoT Hub successfully
- Or, IoT Hub couldn't authenticate the auth header, rule, or key. This could be due to any of the reasons cited in the symptoms.
To resolve this error, no action is needed if using IoT SDK for connection using the device connection string. IoT SDK regenerates the new token to reconnect on SAS token expiration.
The default token lifespan is 60 minutes across SDKs; however, for some SDKs the token lifespan and the token renewal threshold is configurable. Additionally, the errors generated when a device disconnects and reconnects on token renewal differs for each SDK. To learn more, and for information about how to determine which SDK your device is using in logs, see MQTT device disconnect behavior with Azure IoT SDKs and 401003 IoTHubUnauthorized for troubleshooting guide.
Do let us know if you have any further queries.
If an answer is helpful, please click on or upvote
which might help other community members reading this thread.