使用Device Provisoning服务在Azure IoT中心中创建用于创建设备的HTTP请求时出现问题

问题描述

我阅读了这篇有关在Azure IoT中心中创建设备的文章,但在创建sas令牌时遇到了问题,该令牌返回HTTP 401未经授权

https://docs.microsoft.com/en-us/azure/iot-dps/how-to-control-access

这是我创建sas令牌的方法

    private static String ScopE_ID = "0ne0032AAD2";
    private static final String GLOBAL_ENDPOINT = "global.azure-devices-provisioning.net";
    private static final String SYMMETRIC_KEY = "symmetric key from hub";
    private static final String REGISTRATION_ID = "device1";
    public static HttpClient httpClient;
    private static int httpTimeoutInMilliseconds = 24000;**

      public static String generateSasToken() throws Exception {
            // Token will expire in one hour
            var expiry = Instant.Now().getEpochSecond() + 3600;
    
            String stringToSign = URLEncoder.encode(GLOBAL_ENDPOINT,StandardCharsets.UTF_8) + "\n" + expiry;
            byte[] decodedKey = Base64.getDecoder().decode(SYMMETRIC_KEY);
    
            Mac sha256HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(decodedKey,"HmacSHA256");
            sha256HMAC.init(secretKey);
            Base64.Encoder encoder = Base64.getEncoder();
    
            String signature = new String(encoder.encode(
                sha256HMAC.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))),StandardCharsets.UTF_8);
    
            String token = "SharedAccessSignature sr=" + URLEncoder.encode(GLOBAL_ENDPOINT,StandardCharsets.UTF_8)
                    + "&sig=" + URLEncoder.encode(signature,StandardCharsets.UTF_8.name()) + "&se=" + expiry + "&skn=provisioningserviceowner";
                
            return token;
        }

解决方法

看看我的answer(Update-2)及其详细实现(C#)。 基本上,以下输入用于生成sas_token:

  • resourceUri = $“ {scopeId} / registrations / {deviceId}”
  • signingKey = deviceKey
  • policyName =“注册”

endpointAddressUri = $“ https://global.azure-devices-provisioning.net/{scopeId}/registrations/{deviceId}/register?api-version=2019-03-31”;

更新

请注意,已针对应用程序设置中的以下变量配置的 Azure IoT Central 实现了针对性的示例:

  • AzureIoTC_scopeId
  • AzureIoTC_sasToken

如果要通过Azure设备配置服务为 Azure IoT中心注册设备,我们必须使用注册组,请参阅以下内容:

  • Azure DPS ID范围
  • 的值 Azure DPS组的
  • 主键

以下屏幕片段显示了我的示例: enter image description here

deviceKey 是根据DPS注册组(组1)的上述主键和特定的 deviceId 计算得出的。

处理设备注册的azure函数的响应如下(在此示例中为 deviceid = device10101 ):

enter image description here

最后,下图显示了Azure Iot Hub中已注册的设备:

enter image description here