Hello Tim Parsons,
I understand you are encountering a persistent MqttSecurityException ("Not authorized to connect") when connecting Kepware to Azure IoT Hub via MQTT, despite a successful TLS handshake and network validation.
Based on the detailed context you provided, the network and TLS layers are functioning correctly. The error occurring immediately after the TLS handshake confirms that the IoT Hub is rejecting the specific MQTT CONNECT packet credentials.
This is almost exclusively caused by a mismatch in the strict formatting requirements Azure IoT Hub enforces for the MQTT protocol fields (Username, ClientID, and Password). Even a minor deviation here causes an immediate disconnect.
**
I would suggest you to please verify the following three configurations in your Kepware IoT Gateway agent.
1.Validate the MQTT "User Name" Field
This is the most common cause of 401/Not Authorized errors in direct MQTT connections. Azure IoT Hub requires a specific string format that includes the API version. If the api-version is missing, auth fails.
- Format:
{IoT Hub Hostname}/{Device ID}/?api-version=2021-04-12 - Your Configuration should look exactly like this:
IOT-ACC-StAug-DB.azure-devices.net/kepware_acc_staug_002/?api-version=2021-04-12- Check: Ensure the Hub Hostname is the full FQDN.
- Check: Ensure the
/?api-version=2021-04-12is appended at the end.
2.Validate the MQTT "Client ID" Field
In the MQTT protocol, Azure IoT Hub strictly requires the MQTT Client ID to be identical to the Device ID registered in the hub.
- Kepware Setting: In the IoT Gateway agent settings, look for the Client ID field.
- Value:
kepware_acc_staug_002 - Note: If Kepware is generating a random Client ID or appending a string to it, the connection will be rejected.
3.Validate the SAS Token (Password) Structure
You mentioned using Azure CLI to generate the token, which is good. However, confirm the "Resource URI" (sr) embedded within that token matches the casing of your inputs exactly.
- The token should look like:
SharedAccessSignature sr=IOT-ACC-StAug-DB.azure-devices.net%2Fdevices%2Fkepware_acc_staug_002&sig=...&se=... - Double Check: Paste the generated token into the Password field in Kepware. Ensure no trailing spaces were copied.
4.Isolation Test (Recommended)
To rule out Kepware-specific formatting issues, try connecting with a standalone tool like MQTT Explorer or MQTT.fx using the exact same credentials:
- Host:
IOT-ACC-StAug-DB.azure-devices.net - Port: 8883
- Username: (As defined in Step 1)
- Password: (Your SAS Token)
- Client ID:
kepware_acc_staug_002 - TLS: On (CA Certificate required)
If this tool connects successfully, the credentials are valid, and the issue lies in how Kepware is constructing the packet (e.g., hidden characters or specific TLS version settings). If this tool also fails, the issue is definitely with the SAS token generation or Device ID casing.
Reference: