通过 Azure IoT 中心对下游设备进行身份验证Authenticate a downstream device to Azure IoT Hub

在透明网关方案中,与任何其他设备一样,下游设备(有时称为叶设备或子设备)需要在 IoT 中心内拥有标识。In a transparent gateway scenario, downstream devices (sometimes called leaf devices or child devices) need identities in IoT Hub like any other device. 本文将会逐步介绍用于在 IoT 中心对下游设备进行身份验证的选项,然后演示如何声明网关连接。This article walks through the options for authenticating a downstream device to IoT Hub, and then demonstrates how to declare the gateway connection.

成功设置透明网关连接需要完成三个常规步骤。There are three general steps to set up a successful transparent gateway connection. 本文将介绍其中的第二个步骤:This article covers the second step:

  1. 网关设备需要能够安全连接到下游设备,从下游设备接收通信,并将消息路由到正确的目标。The gateway device needs to be able to securely connect to downstream devices, receive communications from downstream devices, and route messages to the proper destination. 有关详细信息,请参阅将 IoT Edge 设备配置为充当透明网关For more information, see Configure an IoT Edge device to act as a transparent gateway.
  2. 下游设备需有一个设备标识,才能在 IoT 中心进行身份验证并知道要通过其网关设备进行通信。The downstream device needs to have a device identity to be able to authenticate with IoT Hub, and know to communicate through its gateway device.
  3. 下游设备需要能够安全连接到其网关设备。The downstream device needs to be able to securely connect to its gateway device. 有关详细信息,请参阅将下游设备连接到 Azure IoT Edge 网关For more information, see Connect a downstream device to an Azure IoT Edge gateway.

下游设备可以使用以下三种方法之一在 IoT 中心进行身份验证:对称密钥(有时称为共享访问密钥)、X.509 自签名证书,或 X.509 证书颁发机构 (CA) 签名的证书。Downstream devices can authenticate with IoT Hub using one of three methods: symmetric keys (sometimes referred to as shared access keys), X.509 self-signed certificates, or X.509 certificate authority (CA) signed certificates. 身份验证步骤用于在 IoT 中心设置任何非 IoT Edge 设备的步骤类似,只是在声明网关关系方面有细微的差别。The authentication steps are similar to the steps used to set up any non-IoT-Edge device with IoT Hub, with small differences to declare the gateway relationship.

本文中的步骤与手动设备预配相关,而与使用 Azure IoT 中心设备预配服务进行的自动预配无关。The steps in this article show manual device provisioning, not automatic provisioning with the Azure IoT Hub Device Provisioning Service.

先决条件Prerequisites

完成配置 IoT Edge 设备以充当透明网关中的步骤。Complete the steps in Configure an IoT Edge device to act as a transparent gateway. 如果要对下游设备使用 X.509 身份验证,则需要使用在透明网关文章中设置的相同的证书生成脚本。If you're using X.509 authentication for your downstream device, you need to use the same certificate generating script that you set up in the transparent gateway article.

本文在多个位置提到了“网关主机名” 。This article refers to the gateway hostname at several points. 网关主机名在 IoT Edge 网关设备上的 config.yaml 文件的 hostname 参数中声明。The gateway hostname is declared in the hostname parameter of the config.yaml file on the IoT Edge gateway device. 它用于创建本文中所用的证书,并在下游设备的连接字符串中引用。It's used to create the certificates in this article, and is referred to in the connection string of the downstream devices. 网关主机名必须能够解析成 IP 地址,不管是使用 DNS 还是主机文件条目。The gateway hostname needs to be resolvable to an IP Address, either using DNS or a host file entry.

对称密钥身份验证Symmetric key authentication

对称密钥身份验证(也称为共享访问密钥身份验证)是在 IoT 中心进行身份验证的最简单方法。Symmetric key authentication, or shared access key authentication, is the simplest way to authenticate with IoT Hub. 使用对称密钥身份验证时,某个 base64 密钥将与 IoT 中心内的 IoT 设备 ID 相关联。With symmetric key authentication, a base64 key is associated with your IoT device ID in IoT Hub. 需将该密钥包含在 IoT 应用程序中,使设备在连接到 IoT 中心时可以出示该密钥。You include that key in your IoT applications so that your device can present it when it connects to IoT Hub.

创建设备标识Create the device identity

使用 Azure 门户、Azure CLI 或适用于 Visual Studio Code 的 IoT 扩展在 IoT 中心添加新的 IoT 设备。Add a new IoT device in your IoT hub, using either the Azure portal, Azure CLI, or the IoT extension for Visual Studio Code. 请记住,需要在 IoT 中心将下游设备标识为常规 IoT 设备,而不是 IoT Edge 设备。Remember that downstream devices need to be identified in IoT Hub as regular IoT device, not IoT Edge devices.

创建新的设备标识时,请提供以下信息:When you create the new device identity, provide the following information:

  • 创建设备的 ID。Create an ID for your device.

  • 选择“对称密钥”作为身份验证类型。 Select Symmetric key as the authentication type.

  • (可选)选择“设置父设备”,并选择下游设备用来建立连接的 IoT Edge 网关设备。 Optionally, choose to Set a parent device and select the IoT Edge gateway device that this downstream device will connect through. 对于对称密钥身份验证,此步骤是可选的,但建议执行此步骤,因为设置父设备可为下游设备启用脱机功能This step is optional for symmetric key authentication, but it's recommended because setting a parent device enables offline capabilities for your downstream device. 以后始终可以更新设备详细信息来添加或更改父设备。You can always update the device details to add or change the parent later.

    在门户中使用对称密钥身份验证创建设备 ID

可以使用适用于 Azure CLI 的 IoT 扩展来完成相同的操作。You can use the IoT extension for Azure CLI to complete the same operation. 以下示例使用对称密钥身份验证创建新的 IoT 设备,并分配父设备:The following example creates a new IoT device with symmetric key authentication and assigns a parent device:

az iot hub device-identity create -n {iothub name} -d {device ID} --pd {gateway device ID}

有关用于创建设备和管理父/子设备的 Azure CLI 命令的详细信息,请参阅 az iot hub device-identity 命令的参考内容。For more information about Azure CLI commands for device creation and parent/child management, see the reference content for az iot hub device-identity commands.

通过网关连接到 IoT 中心Connect to IoT Hub through a gateway

使用对称密钥在 IoT 中心对常规 IoT 设备进行身份验证的过程同样适用于下游设备。The same process is used to authenticate regular IoT devices to IoT Hub with symmetric keys also applies to downstream devices. 唯一的差别在于,需要添加指向网关设备的指针,以路由连接或者在离线场景中代表 IoT 中心处理身份验证。The only difference is that you need to add a pointer to the gateway device to route the connection or, in offline scenarios, to handle the authentication on behalf of IoT Hub.

对于对称密钥身份验证,无需在设备上执行任何附加步骤,即可在 IoT 中心对其进行身份验证。For symmetric key authentication, there's no additional steps that you need to take on your device for it to authenticate with IoT Hub. 仍需准备好证书,使下游设备可以连接到其网关设备。具体请参阅将下游设备连接到 Azure IoT Edge 网关You still need the certificates in place so that your downstream device can connect to its gateway device, as described in Connect a downstream device to an Azure IoT Edge gateway.

在门户中创建 IoT 设备标识后,可以检索其主要密钥或辅助密钥。After creating an IoT device identity in the portal, you can retrieve its primary or secondary keys. 需要将其中的一个密钥包含在要与 IoT 中心通信的任何应用程序中的连接字符串内。One of these keys needs to be included in the connection string that you include in any application that communicates with IoT Hub. 对于对称密钥身份验证,出于方便,IoT 中心将在设备详细信息中提供完整格式的连接字符串。For symmetric key authentication, IoT Hub provides the fully formed connection string in the device details for your convenience. 你需要将有关网关设备的附加信息添加到该连接字符串。You need to add extra information about the gateway device to the connection string.

下游设备的对称密钥连接字符串需要包含以下组成部分:Symmetric key connection strings for downstream devices need the following components:

  • 设备连接到的 IoT 中心:Hostname={iothub name}.azure-devices.netThe IoT hub that the device connects to: Hostname={iothub name}.azure-devices.net
  • 已注册到中心的设备 ID:DeviceID={device ID}The device ID registered with the hub: DeviceID={device ID}
  • 主要密钥或辅助密钥:SharedAccessKey={key}Either the primary or secondary key: SharedAccessKey={key}
  • 设备用来建立连接的网关设备。The gateway device that the device connects through. 请提供 IoT Edge 网关设备 config.yaml 文件中的 hostname 值:GatewayHostName={gateway hostname}Provide the hostname value from the IoT Edge gateway device's config.yaml file: GatewayHostName={gateway hostname}

所有这些组成部分共同构成了如下所示的完整连接字符串:All together, a complete connection string looks like:

HostName=myiothub.azure-devices.cn;DeviceId=myDownstreamDevice;SharedAccessKey=xxxyyyzzz;GatewayHostName=myGatewayDevice

如果你为此下游设备建立了父/子关系,则可以通过直接调用充当连接主机的网关来简化连接字符串。If you established a parent/child relationship for this downstream device, then you can simplify the connection string by calling the gateway directly as the connection host. 例如:For example:

HostName=myGatewayDevice;DeviceId=myDownstreamDevice;SharedAccessKey=xxxyyyzzz

X.509 身份验证X.509 authentication

可通过两种方式使用 X.509 证书对 IoT 设备进行身份验证。There are two ways to authenticate an IoT device using X.509 certificates. 无论选择哪种身份验证方式,将设备连接到 IoT 中心的步骤都是相同的。Whichever way you choose to authenticate, the steps to connect your device to IoT Hub are the same. 选择自签名证书或 CA 签名的证书用于身份验证,然后继续了解如何连接到 IoT 中心。Choose either self-signed or CA-signed certs for authentication, then continue to learn how to connect to IoT Hub.

有关 IoT 中心如何使用 X.509 身份验证的详细信息,请参阅以下文章:For more information about how IoT Hub uses X.509 authentication, see the following articles:

使用 X.509 自签名证书创建设备标识Create the device identity with X.509 self-signed certificates

对于 X.509 自签名身份验证(有时称为指纹身份验证),需要创建新证书并将其放在 IoT 设备上。For X.509 self-signed authentication, sometimes referred to as thumbprint authentication, you need to create new certificates to place on your IoT device. 这些证书包含一个指纹,你可以与 IoT 中心共享该指纹以完成身份验证。These certificates have a thumbprint in them that you share with IoT Hub for authentication.

测试此方案的最简单方法是使用在将 IoT Edge 设备配置为充当透明网关一文中创建证书时所用的同一台计算机。The easiest way to do test this scenario is to use the same machine that you used to create certificates in Configure an IoT Edge device to act as a transparent gateway. 该计算机中应已设置适当的工具、根 CA 证书和中间 CA 证书用于创建 IoT 设备证书。That machine should already be set up with the right tool, root CA certificate, and intermediate CA certificate to create the IoT device certificates. 然后,可将最终的证书及其私钥复制到下游设备。You can copy the final certificates and their private keys over to your downstream device afterwards. 在有关网关的文章中,你已遵循相应的步骤在计算机上设置了 openssl,并克隆了 IoT Edge 存储库用于访问证书创建脚本。Following the steps in the gateway article, you set up openssl on your machine, then cloned the IoT Edge repo to access certificate creation scripts. 然后,创建了一个名为 <WRKDIR> 的工作目录用于保存证书。Then, you made a working directory that we call <WRKDIR> to hold the certificates. 默认证书用于开发和测试,因此有效期仅为 30 天。The default certificates are meant for developing and testing, so only last 30 days. 你应已创建一个根 CA 证书和一个中间证书。You should have created a root CA certificate and an intermediate certificate.

  1. 在 bash 或 PowerShell 窗口中导航到该工作目录。Navigate to your working directory in either a bash or PowerShell window.

  2. 为下游设备创建两个证书(主要和辅助)。Create two certificates (primary and secondary) for the downstream device. 提供设备名称,然后指定主要或辅助标签。Provide your device name and then the primary or secondary label. 此信息用于将文件命名,使你能够跟踪多个设备的证书。This information is used to name the files so that you can keep track of certificates for multiple devices.

    New-CACertsDevice "<device name>-primary"
    New-CACertsDevice "<device name>-secondary"
    
    ./certGen.sh create_device_certificate "<device name>-primary"
    ./certGen.sh create_device_certificate "<device name>-secondary"
    
  3. 检索每个证书的 SHA1 指纹 - 包含 40 个十六进制字符的字符串。Retrieve the SHA1 fingerprint (called a thumbprint in the IoT Hub interface) from each certificate, which is a 40 hexadecimal character string. 使用以下 openssl 命令查看证书并查找指纹:Use the following openssl command to view the certificate and find the fingerprint:

    openssl x509 -in <WORKDIR>/certs/iot-device-<device name>-primary.cert.pem -text -fingerprint | sed 's/[:]//g'
    
  4. 在 Azure 门户中导航到你的 IoT 中心,并使用以下值创建新的 IoT 设备标识:Navigate to your IoT hub in the Azure portal and create a new IoT device identity with the following values:

    • 选择“X.509 自签名”作为身份验证类型。 Select X.509 Self-Signed as the authentication type.
    • 粘贴从设备的主要和辅助证书中复制的十六进制字符串。Paste the hexadecimal strings that you copied from your device's primary and secondary certificates.
    • 选择“设置父设备”,并选择下游设备用来建立连接的 IoT Edge 网关设备。 Select Set a parent device and choose the IoT Edge gateway device that this downstream device will connect through. 对下游设备进行 X.509 身份验证时,需要使用父设备。A parent device is required for X.509 authentication of a downstream device.

    在门户中使用 X.509 自签名身份验证创建设备 ID

  5. 将以下文件复制到下游设备上的任一目录:Copy the following files to any directory on your downstream device:

    • <WRKDIR>\certs\azure-iot-test-only.root.ca.cert.pem
    • <WRKDIR>\certs\iot-device-<device name>*.cert.pem
    • <WRKDIR>\certs\iot-device-<device id>*.cert.pfx
    • <WRKDIR>\certs\iot-device-<device name>*-full-chain.cert.pem
    • <WRKDIR>\private\iot-device-<device name>*.key.pem

    你将在连接到 IoT 中心的叶设备应用程序中引用这些文件。You'll reference these files in the leaf device applications that connect to IoT Hub. 可以使用 Azure Key Vault 之类的服务或安全复制协议之类的功能来移动证书文件。You can use a service like Azure Key Vault or a function like Secure copy protocol to move the certificate files.

可以使用适用于 Azure CLI 的 IoT 扩展来完成相同的设备创建操作。You can use the IoT extension for Azure CLI to complete the same device creation operation. 以下示例使用 X.509 自签名身份验证创建新的 IoT 设备,并分配父设备:The following example creates a new IoT device with X.509 self-signed authentication and assigns a parent device:

az iot hub device-identity create -n {iothub name} -d {device ID} --pd {gateway device ID} --am x509_thumbprint --ptp {primary thumbprint} --stp {secondary thumbprint}

有关用于创建设备、生成证书和管理父/子设备的 Azure CLI 命令的详细信息,请参阅 az iot hub device-identity 命令的参考内容。For more information about Azure CLI commands for device creation, certificate generation, and parent and child management, see the reference content for az iot hub device-identity commands.

使用 X.509 CA 签名的证书创建设备标识Create the device identity with X.509 CA signed certificates

对于 X.509 证书颁发机构 (CA) 签名的身份验证,需要在 IoT 中心注册一个用来为 IoT 设备证书签名的根 CA 证书。For X.509 certificate authority (CA) signed authentication, you need a root CA certificate registered in IoT Hub that you use to sign certificates for your IoT device. 使用根 CA 证书或其任何中间证书颁发的证书的任何设备都可进行身份验证。Any device using a certificate that was issues by the root CA certificate or any of its intermediate certificates will be permitted to authenticate.

本部分基于 IoT 中心文章在 Azure IoT 中心设置 X.509 安全性中详述的说明。This section is based on the instructions detailed in the IoT Hub article Set up X.509 security in your Azure IoT hub. 请遵循本部分所述的步骤了解要使用哪些值来设置通过网关进行连接的下游设备。Follow the steps in this section to know which values to use to set up a downstream device that connects through a gateway.

测试此方案的最简单方法是使用在将 IoT Edge 设备配置为充当透明网关一文中创建证书时所用的同一台计算机。The easiest way to test this scenario is to use the same machine that you used to create certificates in Configure an IoT Edge device to act as a transparent gateway. 该计算机中应已设置适当的工具、根 CA 证书和中间 CA 证书用于创建 IoT 设备证书。That machine should already be set up with the right tool, root CA certificate, and intermediate CA certificate to create the IoT device certificates. 然后,可将最终的证书及其私钥复制到下游设备。You can copy the final certificates and their private keys over to your downstream device afterwards. 在有关网关的文章中,你已遵循相应的步骤在计算机上设置了 openssl,并克隆了 IoT Edge 存储库用于访问证书创建脚本。Following the steps in the gateway article, you set up openssl on your machine, then cloned the IoT Edge repo to access certificate creation scripts. 然后,创建了一个名为 <WRKDIR> 的工作目录用于保存证书。Then, you made a working directory that we call <WRKDIR> to hold the certificates. 默认证书用于开发和测试,因此有效期仅为 30 天。The default certificates are meant for developing and testing, so only last 30 days. 你应已创建一个根 CA 证书和一个中间证书。You should have created a root CA certificate and an intermediate certificate.

  1. 请遵照“在 Azure IoT 中心设置 X.509 安全性”的将 X.509 CA 证书注册到 IoT 中心部分中的说明操作。 Follow the instructions in the Register X.509 CA certificates to your IoT hub section of Set up X.509 security in your Azure IoT hub. 在本部分,你将执行以下步骤:In that section, you perform the following steps:

    1. 上传根 CA 证书。Upload a root CA certificate. 如果使用的证书是在有关透明网关的文章中创建的,请上传 <WRKDIR>/certs/azure-iot-test-only.root.ca.cert.pem 作为根证书文件。If you're using the certificates that you created in the transparent gateway article, upload <WRKDIR>/certs/azure-iot-test-only.root.ca.cert.pem as the root certificate file.

    2. 验证你是否拥有该根 CA 证书。Verify that you own that root CA certificate. 可以使用 <WRKDIR> 中的证书工具验证拥有权。You can verify possession with the cert tools in <WRKDIR>.

      New-CACertsVerificationCert "<verification code from Azure portal>"
      
      ./certGen.sh create_verification_certificate <verification code from Azure portal>"
      
  2. 请遵照“在 Azure IoT 中心设置 X.509 安全性”的为 IoT 中心创建 X.509 设备部分中的说明操作。 Follow the instructions in the Create an X.509 device for your IoT hub section of Set up X.509 security in your Azure IoT hub. 在本部分,你将执行以下步骤:In that section, you perform the following steps:

    1. 添加新设备。Add a new device. 设备 ID 提供小写名称,并选择身份验证类型“X.509 CA 签名”。 Provide a lowercase name for device ID, and choose the authentication type X.509 CA Signed.
    2. 设置父设备。Set a parent device. 对于下游设备,请选择“设置父设备”,并选择用来与 IoT 中心建立连接的 IoT Edge 网关设备。 For downstream devices, select Set a parent device and choose the IoT Edge gateway device that will provide the connection to IoT Hub.
  3. 创建下游设备的证书链。Create a certificate chain for your downstream device. 使用上传到 IoT 中心的同一根 CA 证书来建立此链。Use the same root CA certificate that you uploaded to IoT Hub to make this chain. 使用在门户中提供给设备标识的相同小写设备 ID。Use the same lowercase device ID that you gave to your device identity in the portal.

    New-CACertsDevice "<device id>"
    
    ./certGen.sh create_device_certificate "<device id>"
    
  4. 将以下文件复制到下游设备上的任一目录:Copy the following files to any directory on your downstream device:

    • <WRKDIR>\certs\azure-iot-test-only.root.ca.cert.pem
    • <WRKDIR>\certs\iot-device-<device id>*.cert.pem
    • <WRKDIR>\certs\iot-device-<device id>*.cert.pfx
    • <WRKDIR>\certs\iot-device-<device id>*-full-chain.cert.pem
    • <WRKDIR>\private\iot-device-<device id>*.key.pem

    你将在连接到 IoT 中心的叶设备应用程序中引用这些文件。You'll reference these files in the leaf device applications that connect to IoT Hub. 可以使用 Azure Key Vault 之类的服务或安全复制协议之类的功能来移动证书文件。You can use a service like Azure Key Vault or a function like Secure copy protocol to move the certificate files.

可以使用适用于 Azure CLI 的 IoT 扩展来完成相同的设备创建操作。You can use the IoT extension for Azure CLI to complete the same device creation operation. 以下示例使用 X.509 CA 签名身份验证创建新的 IoT 设备,并分配父设备:The following example creates a new IoT device with X.509 CA signed authentication and assigns a parent device:

az iot hub device-identity create -n {iothub name} -d {device ID} --pd {gateway device ID} --am x509_ca

有关用于创建设备和管理父/子设备的 Azure CLI 命令的详细信息,请参阅 az iot hub device-identity 命令的参考内容。For more information about Azure CLI commands for device creation and parent/child management, see the reference content for az iot hub device-identity commands.

通过网关连接到 IoT 中心Connect to IoT Hub through a gateway

每个 Azure IoT SDK 处理 X.509 身份验证的方式略有不同。Each Azure IoT SDK handles X.509 authentication a little differently. 但是,使用 X.509 证书在 IoT 中心对常规 IoT 设备进行身份验证的过程同样适用于下游设备。However, the same process is used to authenticate regular IoT devices to IoT Hub with X.509 certificates also applies to downstream devices. 唯一的差别在于,需要添加指向网关设备的指针,以路由连接或者在离线场景中代表 IoT 中心处理身份验证。The only difference is that you need to add a pointer to the gateway device to route the connection or, in offline scenarios, to handle the authentication on behalf of IoT Hub. 一般情况下,可对所有 IoT 中心设备遵循相同的 X.509 身份验证步骤,只需将连接字符串中的 Hostname 值替换为网关设备的主机名即可。In general, you can follow the same X.509 authentication steps for all IoT Hub devices, then simply replace the value of Hostname in the connection string to be the hostname of your gateway device.

以下部分演示了不同 SDK 语言的一些示例。The following sections show some examples for different SDK languages.

Important

以下示例演示 IoT 中心 SDK 如何使用证书对设备进行身份验证。The following samples demonstrate how the IoT Hub SDKs use certificates to authenticate devices. 在生产部署中,应在硬件安全模块 (HSM) 中存储私钥或 SAS 密钥等所有机密。In a production deployment, you should store all secrets like private or SAS keys in a hardware secure module (HSM).

.NET.NET

有关使用 X.509 证书在 IoT 中心进行身份验证的 C# 程序示例,请参阅在 Azure IoT 中心设置 X.509 安全性For an example of a C# program authenticating to IoT Hub with X.509 certificates, see Set up X.509 security in your Azure IoT hub. 此处包含了该示例的某些关键代码行,以演示身份验证过程。Some of the key lines of that sample are included here to demonstrate the authentication process.

在声明 DeviceClient 实例的主机名时,请使用 IoT Edge 网关设备的主机名。When declaring the hostname for your DeviceClient instance, use the IoT Edge gateway device's hostname. 可在网关设备的 config.yaml 文件中找到该主机名。The hostname can be found in the gateway device's config.yaml file.

如果使用 IoT Edge Git 存储库提供的测试证书,该证书的密钥为 1234If you're using the test certificates provided by the IoT Edge git repository, the key to the certificates is 1234.

try
{
    var cert = new X509Certificate2(@"<absolute-path-to-your-device-pfx-file>", "1234");
    var auth = new DeviceAuthenticationWithX509Certificate("<device-id>", cert);
    var deviceClient = DeviceClient.Create("<gateway hostname>", auth, TransportType.Amqp_Tcp_Only);

    if (deviceClient == null)
    {
        Console.WriteLine("Failed to create DeviceClient!");
    }
    else
    {
        Console.WriteLine("Successfully created DeviceClient!");
        SendEvent(deviceClient).Wait();
    }

    Console.WriteLine("Exiting...\n");
}
catch (Exception ex)
{
    Console.WriteLine("Error in sample: {0}", ex.Message);
}

CC

有关使用 X.509 证书在 IoT 中心进行身份验证的 C 程序示例,请参阅 C IoT SDK 的 iotedge_downstream_device_sample 示例。For an example of a C program authenticating to IoT Hub with X.509 certificates, see the C IoT SDK's iotedge_downstream_device_sample sample. 此处包含了该示例的某些关键代码行,以演示身份验证过程。Some of the key lines of that sample are included here to demonstrate the authentication process.

定义下游设备的连接字符串时,请对 HostName 参数使用 IoT Edge 网关设备的主机名。When defining the connection string for your downstream device, use the IoT Edge gateway device's hostname for the HostName parameter. 可在网关设备的 config.yaml 文件中找到该主机名。The hostname can be found in the gateway device's config.yaml file.

// If your downstream device uses X.509 authentication (self signed or X.509 CA) then
// resulting connection string should look like the following:
// "HostName=<gateway device hostname>;DeviceId=<device_id>;x509=true"
static const char* connectionString = "[Downstream device IoT Edge connection string]";

// Path to the Edge "owner" root CA certificate
static const char* edge_ca_cert_path = "[Path to root CA certificate]";

// When the downstream device uses X.509 authentication, a certificate and key 
// in PRM format must be provided.
static const char * x509_device_cert_path = "[Path to primary or secondary device cert]";
static const char * x509_device_key_path = "[Path to primary or secondary device key]";

int main(void)
{
    // Create the iothub handle here
    device_handle = IoTHubDeviceClient_CreateFromConnectionString(connectionString, protocol);

    // Provide the Azure IoT device client with the same root
    // X509 CA certificate that was used to set up the IoT Edge gateway runtime
    if (edge_ca_cert_path != NULL)
    {
        cert_string = obtain_edge_ca_certificate();
        (void)IoTHubDeviceClient_SetOption(device_handle, OPTION_TRUSTED_CERT, cert_string);
    }

    if ((x509_device_cert_path != NULL) && (x509_device_key_path != NULL))
    {
        const char *x509certificate = obtain_file_contents(x509_device_cert_path);
        const char *x509privatekey = obtain_file_contents(x509_device_key_path);
        if ((IoTHubDeviceClient_SetOption(device_handle, OPTION_X509_CERT, x509certificate) != IOTHUB_CLIENT_OK) ||
            (IoTHubDeviceClient_SetOption(device_handle, OPTION_X509_PRIVATE_KEY, x509privatekey) != IOTHUB_CLIENT_OK)
            )
        {
            printf("failure to set options for x509, aborting\r\n");
            exit(1);
        }
    }
}

Node.jsNode.js

有关使用 X.509 证书在 IoT 中心进行身份验证的 Node.js 程序示例,请参阅 Node.js IoT SDK 的 simple_sample_device_x509.js 示例。For an example of a Node.js program authenticating to IoT Hub with X.509 certificates, see the Node.js IoT SDK's simple_sample_device_x509.js sample. 此处包含了该示例的某些关键代码行,以演示身份验证过程。Some of the key lines of that sample are included here to demonstrate the authentication process.

定义下游设备的连接字符串时,请对 HostName 参数使用 IoT Edge 网关设备的主机名。When defining the connection string for your downstream device, use the IoT Edge gateway device's hostname for the HostName parameter. 可在网关设备的 config.yaml 文件中找到该主机名。The hostname can be found in the gateway device's config.yaml file.

如果使用 IoT Edge Git 存储库提供的测试证书,该证书的密钥为 1234If you're using the test certificates provided by the IoT Edge git repository, the key to the certificates is 1234.

// String containing Hostname and Device Id in the following format:
//  "HostName=<gateway device hostname>;DeviceId=<device_id>;x509=true"
var connectionString = '<DEVICE CONNECTION STRING WITH x509=true>';
var certFile = '<PATH-TO-CERTIFICATE-FILE>';
var keyFile = '<PATH-TO-KEY-FILE>';
var passphrase = '<KEY PASSPHRASE IF ANY>';

// fromConnectionString must specify a transport constructor, coming from any transport package.
var client = Client.fromConnectionString(connectionString, Protocol);

var options = {
   cert : fs.readFileSync(certFile, 'utf-8').toString(),
   key : fs.readFileSync(keyFile, 'utf-8').toString(),
   passphrase: passphrase
 };

// Calling setOptions with the x509 certificate and key (and optionally, passphrase) will configure the client transport to use x509 when connecting to IoT Hub
client.setOptions(options);

PythonPython

Python SDK 目前仅支持使用文件中的 X509 证书和密钥,不支持内联定义的证书和密钥。The Python SDK currently only supports using X509 certificates and and keys from files, not ones which are defined inline. 在以下示例中,相关文件路径存储在环境变量中。In the following example, relevant filepaths are stored in environment variables.

定义下游设备的主机名时,请对 HostName 参数使用 IoT Edge 网关设备的主机名。When defining the hostname for your downstream device, use the IoT Edge gateway device's hostname for the HostName parameter. 可在网关设备的 config.yaml 文件中找到该主机名。The hostname can be found in the gateway device's config.yaml file.

import os
from azure.iot.device import IoTHubDeviceClient, X509

HOSTNAME = "[IoT Edge Gateway Hostname]"
DEVICE_ID = "[Device ID]"

def iothub_client_init():
    x509 = X509(
        cert_file=os.getenv("X509_CERT_FILE"),
        key_file=os.getenv("X509_KEY_FILE")
    )

    client = IoTHubDeviceClient.create_from_x509_certificate(
        x509=x509,
        hostname=HOSTNAME,
        device_id=DEVICE_ID
    )
)

if __name__ == '__main__':
    iothub_client_init()

JavaJava

有关使用 X.509 证书在 IoT 中心进行身份验证的 Java 程序示例,请参阅 Java IoT SDK 的 SendEventX509.java 示例。For an example of a Java program authenticating to IoT Hub with X.509 certificates, see the Java IoT SDK's SendEventX509.java sample. 此处包含了该示例的某些关键代码行,以演示身份验证过程。Some of the key lines of that sample are included here to demonstrate the authentication process.

定义下游设备的连接字符串时,请对 HostName 参数使用 IoT Edge 网关设备的主机名。When defining the connection string for your downstream device, use the IoT Edge gateway device's hostname for the HostName parameter. 可在网关设备的 config.yaml 文件中找到该主机名。The hostname can be found in the gateway device's config.yaml file.

//PEM encoded representation of the public key certificate
private static String publicKeyCertificateString =
    "-----BEGIN CERTIFICATE-----\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "-----END CERTIFICATE-----\n";

//PEM encoded representation of the private key
private static String privateKeyString =
    "-----BEGIN EC PRIVATE KEY-----\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
    "-----END EC PRIVATE KEY-----\n";

DeviceClient client = new DeviceClient(connectionString, protocol, publicKeyCertificateString, false, privateKeyString, false);

后续步骤Next steps

完成本文后,你应已获得一个充当透明网关的 IoT Edge 设备,以及一个已注册到 IoT 中心的下游设备。By completing this article, you should have an IoT Edge device working as a transparent gateway and a downstream device registered with an IoT hub. 接下来,需要配置下游设备,以信任网关设备并向其发送消息。Next, you need to configure your downstream devices to trust the gateway device and send messages to it. 有关详细信息,请参阅将下游设备连接到 Azure IoT Edge 网关For more information, see Connect a downstream device to an Azure IoT Edge gateway.