使用设备配置服务在 azure iot hub 中创建用于创建设备的 HTTP 请求的问题

Problems with creating HTTP request for creating device in azure iot hub using Device Provisoning service

我阅读了这篇关于在 azure iot hub 中创建设备的文章,但我在创建 sas 令牌时遇到了问题,return 我 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 组的值主键

以下屏幕片段显示了我的示例:

deviceKey 是根据 DPS 注册组 (group1) 的上述 主键 和特定 deviceId.

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

最后,下图是Azure Iot Hub中注册的设备: