快速入门:使用 Node.js 将 X.509 设备注册到设备预配服务Quickstart: Enroll X.509 devices to the Device Provisioning Service using Node.js

在本快速入门中,你将使用 Node.js 以编程方式创建使用中间或根 CA X.509 证书的注册组。In this quickstart, you use Node.js to programmatically create an enrollment group that uses intermediate or root CA X.509 certificates. 该注册组是使用用于 Node.js 的 IoT SDK 和一个示例 Node.js 应用程序创建的。The enrollment group is created using the IoT SDK for Node.js and a sample Node.js application.

先决条件Prerequisites

准备测试证书Prepare test certificates

对于本快速入门,必须具有一个包含中间或根 CA X.509 证书的公共部分的 .pem 或.cer 文件。For this quickstart, you must have a .pem or a .cer file that contains the public portion of an intermediate or root CA X.509 certificate. 此证书必须上传到预配服务,并由该服务进行验证。This certificate must be uploaded to your provisioning service, and verified by the service.

若要详细了解如何将基于 X.509 证书的公钥基础结构 (PKI) 与 Azure IoT 中心和设备预配服务配合使用,请参阅 X.509 CA 证书安全概述For more information about using X.509 certificate-based Public Key Infrastructure (PKI) with Azure IoT Hub and Device Provisioning Service, see X.509 CA certificate security overview.

Azure IoT C SDK 包含的测试工具可以帮助你创建 X.509 证书链、从该链上传根证书或中间证书,以及通过服务执行所有权证明操作,对证书进行验证。The Azure IoT C SDK contains test tooling that can help you create an X.509 certificate chain, upload a root or intermediate certificate from that chain, and perform proof-of-possession with the service to verify the certificate. 根据设计,使用 SDK 工具创建的证书只能用于开发测试Certificates created with the SDK tooling are designed to use for development testing only. 这些证书不得在生产环境中使用These certificates must not be used in production. 它们包含硬编码的密码(“1234”),在 30 天后过期。They contain hard-coded passwords ("1234") that expire after 30 days. 若要了解如何获取适用于生产用途的证书,请参阅 Azure IoT 中心文档中的如何获取 X.509 CA 证书To learn about obtaining certificates suitable for production use, see How to get an X.509 CA certificate in the Azure IoT Hub documentation.

若要使用此测试工具来生成证书,请执行以下步骤:To use this test tooling to generate certificates, perform the following steps:

  1. 找到最新版 Azure IoT C SDK 的标记名称。Find the tag name for the latest release of the Azure IoT C SDK.

  2. 打开命令提示符或 Git Bash shell,并切换到计算机上的某个工作文件夹。Open a command prompt or Git Bash shell, and change to a working folder on your machine. 运行以下命令,克隆最新版 Azure IoT C SDK GitHub 存储库。Run the following commands to clone the latest release of the Azure IoT C SDK GitHub repository. 使用在上一步找到的标记作为 -b 参数的值:Use the tag you found in the previous step as the value for the -b parameter:

    git clone -b <release-tag> https://github.com/Azure/azure-iot-sdk-c.git
    cd azure-iot-sdk-c
    git submodule update --init
    

    应该预料到此操作需要几分钟才能完成。You should expect this operation to take several minutes to complete.

    测试工具位于你克隆的存储库的 azure-iot-sdk-c/tools/CACertificates 中。The test tooling is located in the azure-iot-sdk-c/tools/CACertificates of the repository you cloned.

  3. 根据管理示例和教程的测试 CA 证书中的步骤进行操作。Follow the steps in Managing test CA certificates for samples and tutorials.

创建注册组示例Create the enrollment group sample

Azure IoT 设备预配服务支持两类注册:The Azure IoT Device Provisioning Service supports two types of enrollments:

注册组可以控制对设备的预配服务的访问,此类设备在其证书链中共享常用签名证书。An enrollment group controls access to the provisioning service for devices that share a common signing certificate in their certificate chain. 若要了解详细信息,请参阅使用 X.509 证书控制设备对预配服务的访问To learn more, see Controlling device access to the provisioning service with X.509 certificates.

  1. 在工作文件夹的命令窗口中,运行以下命令:From a command window in your working folder, run:

    npm install azure-iot-provisioning-service
    
  2. 使用文本编辑器,在工作文件夹中创建 create_enrollment_group.js 文件。Using a text editor, create a create_enrollment_group.js file in your working folder. 将以下代码添加到文件并进行保存:Add the following code to the file and save:

    'use strict';
    var fs = require('fs');
    
    var provisioningServiceClient = require('azure-iot-provisioning-service').ProvisioningServiceClient;
    
    var serviceClient = provisioningServiceClient.fromConnectionString(process.argv[2]);
    
    var enrollment = {
      enrollmentGroupId: 'first',
      attestation: {
        type: 'x509',
        x509: {
          signingCertificates: {
            primary: {
              certificate: fs.readFileSync(process.argv[3], 'utf-8').toString()
            }
          }
        }
      },
      provisioningStatus: 'disabled'
    };
    
    serviceClient.createOrUpdateEnrollmentGroup(enrollment, function(err, enrollmentResponse) {
      if (err) {
        console.log('error creating the group enrollment: ' + err);
      } else {
        console.log("enrollment record returned: " + JSON.stringify(enrollmentResponse, null, 2));
        enrollmentResponse.provisioningStatus = 'enabled';
        serviceClient.createOrUpdateEnrollmentGroup(enrollmentResponse, function(err, enrollmentResponse) {
          if (err) {
            console.log('error updating the group enrollment: ' + err);
          } else {
            console.log("updated enrollment record returned: " + JSON.stringify(enrollmentResponse, null, 2));
          }
        });
      }
    });
    

运行注册组示例Run the enrollment group sample

  1. 若要运行示例,需要适用于预配服务的连接字符串。To run the sample, you need the connection string for your provisioning service.

    1. 登录到 Azure 门户,选择左侧菜单上的“所有资源”按钮,打开设备预配服务 。Sign in to the Azure portal, select the All resources button on the left-hand menu and open your Device Provisioning service.

    2. 单击“共享访问策略”,然后选择需要用来打开其属性的访问策略。 Click Shared access policies, then select the access policy you want to use to open its properties. 在“访问策略”窗口中,复制并记下主密钥连接字符串。 In the Access Policy window, copy and note down the primary key connection string.

      从门户获取预配服务连接字符串

  2. 准备测试证书中所述,还需要一个 .pem 文件,其中包含的 X.509 中间或根 CA 证书此前已上传并通过预配服务进行验证。As stated in Prepare test certificates, you also need a .pem file that contains an X.509 intermediate or root CA certificate that has been previously uploaded and verified with your provisioning service. 若要查看证书是否已上传并验证,请在 Azure 门户的设备预配服务摘要页中选择“证书”。 To check that your certificate has been uploaded and verified, on the Device Provisioning Service summary page in the Azure portal, select Certificates. 找到要用于组注册的证书,确保其状态值为“已验证”。 Find the certificate that you want to use for the group enrollment and ensure that its status value is verified.

    门户中的已验证证书

  3. 若要为证书创建注册组,请运行以下命令(在命令参数两侧添加引号):To create an enrollment group for your certificate, run the following command (include the quotes around the command arguments):

    node create_enrollment_group.js "<the connection string for your provisioning service>" "<your certificate's .pem file>"
    
  4. 成功创建以后,命令窗口会显示新的注册组的属性。On successful creation, the command window displays the properties of the new enrollment group.

    命令输出中的注册属性

  5. 验证注册组是否已创建。Verify that the enrollment group has been created. 在 Azure 门户的设备预配服务摘要边栏选项卡上,选择“管理注册” 。In the Azure portal, on the Device Provisioning Service summary blade, select Manage enrollments. 选择“注册组”选项卡,验证新注册项 (first) 是否存在。 Select the Enrollment Groups tab and verify that the new enrollment entry (first) is present.

    门户中的注册属性

清理资源Clean up resources

如果打算学习 Node.js 服务示例,请勿清除本快速入门中创建的资源。If you plan to explore the Node.js service samples, do not clean up the resources created in this quickstart. 如果不打算继续学习,请通过以下步骤删除通过本快速入门创建的所有 Azure 资源。If you do not plan to continue, use the following steps to delete all Azure resources created by this quickstart.

  1. 关闭计算机上的 Node.js 示例输出窗口。Close the Node.js sample output window on your machine.
  2. 在 Azure 门户中导航到设备预配服务,选择“管理注册”,然后选择“注册组”选项卡 。选中通过本快速入门注册的 X.509 设备的“组名称”旁边的复选框,然后按窗格顶部的“删除”按钮 。Navigate to your Device Provisioning service in the Azure portal, select Manage enrollments, and then select the Enrollment Groups tab. Select the check box next to the GROUP NAME for the X.509 devices you enrolled using this quickstart, and press the Delete button at the top of the pane.
  3. 在 Azure 门户的设备预配服务中选择“证书”,然后选择为本快速入门上传的证书,再按“证书详细信息”窗口顶部的“删除”按钮。 From your Device Provisioning service in the Azure portal, select Certificates, select the certificate you uploaded for this quickstart, and press the Delete button at the top of the Certificate Details window.

后续步骤Next steps

本快速入门介绍了如何使用 Azure IoT 中心设备预配服务为 X.509 中间或根 CA 证书创建组注册。In this quickstart, you created a group enrollment for an X.509 intermediate or root CA certificate using the Azure IoT Hub Device Provisioning Service. 若要深入了解设备预配,请继续学习本教程有关如何在 Azure 门户中进行设备预配服务设置的内容。To learn about device provisioning in depth, continue to the tutorial for the Device Provisioning Service setup in the Azure portal.

另请参阅 Node.js 设备预配示例Also, see the Node.js device provisioning sample.