2

我正在尝试直接使用 MQTT 连接到 IOT 中心。

我只是遵循以下文档,
https ://docs.microsoft.com/en-us/azure/iot-central/concepts-connectivity#connect-a-single-device
https://www.instructables.com/id/Azure -IoT-Hub-Set-Up-MQTTfx-Sigfox-Callback-and-Dr/
https://github.com/MediaTek-Labs/aws_mbedtls_mqtt/pull/9/files?short_path=04c6e90
https://docs.azure。 cn/zh-cn/articles/azure-operations-guide/iot-hub/aog-iot-hub-howto-connect-with-tool-mqtt-fx(翻译成英文)

以上文档我使用来自 github 的 dps_cstr 工具通过此链接生成带有 SAS 令牌的连接字符串
https://docs.microsoft.com/en-us/azure/iot-central/tutorial-add-device#prepare-the-client-代码

Broker Address = saas-iothub-947867dc-cd5d-446c-90ff-e0f964f020fe.azure-devices.net  
Broker port = 8883  
Client ID = 92ff3e25-00e5-4249-9074  
User Name = saas-iothub-947867dc-cd5d-446c-90ff.azure-devices.net/92ff3e25-00e5-4249-9074  
MQTT Version = 3.1.1  
Password = OfAlY0BGstmuinZzOcdDDf  

我已经使用上面的连接字符串和详细信息为 iot Central 配置了带有连接配置文件的 MQTT.fx。附上那个快照 折断 当我尝试连接到这个时,我收到一个错误“未授权连接”。
日志:

2018-12-20 00:42:49,738  INFO --- BrokerConnectorController      : onConnect
2018-12-20 00:42:49,740  INFO --- ScriptsController              : Clear console.
2018-12-20 00:42:49,804  INFO --- MqttFX ClientModel             : MqttClient with ID 92ff3e25-00e5-4249-9074-854b43b5a949 assigned.
2018-12-20 00:42:53,571 ERROR --- MqttFX ClientModel             : Error when connecting
org.eclipse.paho.client.mqttv3.MqttSecurityException: Not authorized to connect
    at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
    at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
    at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_181]
    at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_181]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) ~[?:1.8.0_181]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[?:1.8.0_181]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_181]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_181]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_181]
2018-12-20 00:42:53,572 ERROR --- MqttFX ClientModel             : Please verify your Settings (e.g. Broker Address, Broker Port & Client ID) and the user credentials!
org.eclipse.paho.client.mqttv3.MqttSecurityException: Not authorized to connect
    at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
    at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
    at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_181]
    at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_181]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) ~[?:1.8.0_181]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[?:1.8.0_181]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_181]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_181]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_181]
2018-12-20 00:42:53,574  INFO --- ScriptsController              : Clear console.
2018-12-20 00:42:53,574 ERROR --- BrokerConnectService           : Not authorized to connect

编辑:我从https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c
创建了一个 CA 证书作为 CACert.cer

我在 SSL/TLS 选项中选择了 CS 证书文件选项并再次尝试。但我有同样的错误

4

1 回答 1

3

我刚刚使用连接到 Azure IoT Central 的 MQTT.fx 客户端完成了一项测试。根据文档直接使用 MQTT 协议,密码必须采用以下格式,请参见示例:

SharedAccessSignature sr={your hub name}.azure-devices.net%2Fdevices%2FMyDevice01%2Fapi-version%3D2016-11-14&sig=vSgHBMUG.....Ntg%3d&se=1456481802

您必须生成上述密码(sas 令牌)字符串。您可以使用以下辅助函数:

string sasToken = SharedAccessSignatureBuilder.GetSASTokenFromConnectionString(connectionString);


public sealed class SharedAccessSignatureBuilder
{ 
    public static string GetHostNameNamespaceFromConnectionString(string connectionString)
    {
        return GetPartsFromConnectionString(connectionString)["HostName"].Split('.').FirstOrDefault();
    }
    public static string GetSASTokenFromConnectionString(string connectionString, uint hours = 24)
    {
        var parts = GetPartsFromConnectionString(connectionString);
        return GetSASToken(parts["HostName"], parts["SharedAccessKey"], parts.Keys.Contains("SharedAccessKeyName") ? parts["SharedAccessKeyName"] : null, hours);
    }
    public static string GetSASToken(string resourceUri, string key, string keyName = null, uint hours = 24)
    {
        var expiry = GetExpiry(hours);
        string stringToSign = System.Web.HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
        HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
        var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry);
        if(!string.IsNullOrEmpty(keyName))
            sasToken += String.Format(CultureInfo.InvariantCulture, "&skn={0}", keyName); 

        return sasToken;
    }

    #region Helpers
    private static Dictionary<string, string> GetPartsFromConnectionString(string connectionString)
    {
        return connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new[] { '=' }, 2)).ToDictionary(x => x[0].Trim(), x => x[1].Trim());
    }

    // default expiring = 24 hours
    private static string GetExpiry(uint hours = 24)
    {
        TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
        return Convert.ToString((int)sinceEpoch.TotalSeconds + 3600 * hours);
    }
    #endregion
}

以下屏幕片段显示了连接到 Azure IoT Central 和设备仪表板的 MQTT.fx 设备 (myfirstdevice)。

在此处输入图像描述

在此处输入图像描述

于 2018-12-19T21:02:21.787 回答