是否可以使用自行/CA 创建的证书以编程方式将新设备注册到 azure iot-hub 上?
例如,我想将我的树莓派从同一个树莓派注册到我新创建的 IOT-HUB 上。我知道我们可以使用 AZ Cli 来做到这一点。我正在寻找是否有一种方法可以使用 MQTT/REST 以编程方式完成此操作?
提前致谢。
问候, 普拉迪普
最佳答案
您可以使用设备配置服务 - DPS。 DPS 是另一项服务,其目的是识别您的设备,如果 DPS 识别出设备标识,DPS 将在您的 IoT 中心创建一个身份。
您可以通过创建单独注册(对于单个设备加入)或组注册(对于一组设备,通常如果您使用证书或共享访问 key 身份验证类型)来设置 DPS。 注册通常包含设备应提供的标识类型,以及应将具有所提供标识的设备分配到的 IoT 中心。
典型的流程是设备使用一些公共(public)标识(证书链、TPM 注册 ID 或 SAS key )联系 DPS。然后在内部,DPS 可以挑战设备( proof-of-possesion in case of CA certificates ),如果设备成功解决挑战,则意味着该设备包含标识该设备的特定 secret (在 CA 证书的情况下为私钥),因此 DPS将在该特定注册中为分配的集线器创 build 备标识。这个过程称为attestation .
因此,在设备端,您至少会收到 IoT 中心端点以及用于与 IoT 中心通信的设备 ID。
下面是如何使用 CA 证书和 C# 执行此操作的代码片段:
var certificate = new X509Certificate2(leafCertificatePath, leafCertificatePassword);
using (var security = new SecurityProviderX509Certificate(certificate))
using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
{
ProvisioningDeviceClient provClient =
ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, dpsScope, security, transport);
var deviceAuthentication = await GetDeviceRegistrationResultAsync(provClient, security);
var auth = new DeviceAuthenticationWithX509Certificate(deviceAuthentication.DeviceId, security.GetAuthenticationCertificate());
var deviceClient = DeviceClient.Create(hostname: deviceAuthentication.AssignedHub,
authenticationMethod: auth,
transportType: TransportType.Mqtt);
if (deviceClient == null)
{
Console.WriteLine("Failed to create DeviceClient!");
}
else
{
SendEvents(deviceClient, MESSAGE_COUNT).Wait();
}
}
从DPS获取设备注册结果的方法:
static async Task<DeviceRegistrationResult> GetDeviceRegistrationResultAsync(ProvisioningDeviceClient provClient, SecurityProviderX509 security)
{
DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);
if (result.Status != ProvisioningRegistrationStatusType.Assigned)
{
throw new Exception("Device not assigned");
}
return result;
}
来自 MSFT 的官方示例,您可以找到 here
Here这是您使用 IoT 中心和 DPS 创建和验证证书的方式。
关于azure - 使用 mqtt 以编程方式在 Azure IoT-hub 上注册设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65911888/