Skip to content

Latest commit

 

History

History
58 lines (45 loc) · 3.29 KB

File metadata and controls

58 lines (45 loc) · 3.29 KB
title How to connect a device to IoT Hub using a certificate (.NET)
titleSuffix Azure IoT Hub
description Learn how to connect a device to IoT Hub using a certificate and the Azure IoT Hub SDK for .NET.
author SoniaLopezBravo
ms.author sonialopez
ms.service iot-hub
ms.devlang csharp
ms.topic include
ms.manager lizross
ms.date 12/12/2024
ms.custom mqtt, devx-track-csharp, devx-track-dotnet

To connect a device to IoT Hub using an X.509 certificate:

  1. Use DeviceAuthenticationWithX509Certificate to create an object that contains device and certificate information. DeviceAuthenticationWithX509Certificate is passed as the second parameter to DeviceClient.Create (step 2).

  2. Use DeviceClient.Create to connect the device to IoT Hub using an X.509 certificate.

In this example, device and certificate information is populated in the auth DeviceAuthenticationWithX509Certificate object that is passed to DeviceClient.Create.

This example shows certificate input parameter values as local variables for clarity. In a production system, store sensitive input parameters in environment variables or another more secure storage location. For example, use Environment.GetEnvironmentVariable("HOSTNAME") to read the host name environment variable.

RootCertPath = "~/certificates/certs/sensor-thl-001-device.cert.pem";
Intermediate1CertPath = "~/certificates/certs/sensor-thl-001-device.intermediate1.cert.pem";
Intermediate2CertPath = "~/certificates/certs/sensor-thl-001-device.intermediate2.cert.pem";
DevicePfxPath = "~/certificates/certs/sensor-thl-001-device.cert.pfx";
DevicePfxPassword = "1234";
DeviceName = "MyDevice";
HostName = "xxxxx.azure-devices.net";

var chainCerts = new X509Certificate2Collection();
chainCerts.Add(new X509Certificate2(RootCertPath));
chainCerts.Add(new X509Certificate2(Intermediate1CertPath));
chainCerts.Add(new X509Certificate2(Intermediate2CertPath));
using var deviceCert = new X509Certificate2(DevicePfxPath, DevicePfxPassword);
using var auth = new DeviceAuthenticationWithX509Certificate(DeviceName, deviceCert, chainCerts);

using var deviceClient = DeviceClient.Create(
    HostName,
    auth,
    TransportType.Amqp);

For more information about certificate authentication, see:

Code samples

For working samples of device X.509 certificate authentication, see: