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

本快速入门展示了如何使用 Java 以编程方式将一组 X.509 模拟设备注册到 Azure IoT 中心设备预配服务。This quickstart shows how to use Java to programmatically enroll a group of X.509 simulated devices to the Azure IoT Hub Device Provisioning Service. 通过创建注册组个人注册将设备注册到预配服务实例。Devices are enrolled to a provisioning service instance by creating an Enrollment group, or an Individual enrollment. 本快速入门展示了如何创建这两种类型的注册。This quickstart shows how to create both types of enrollments. 该注册是在参考示例 Java 应用程序的情况下使用 Java 服务 SDK 创建的。The enrollments are created using the Java Service SDK with the help of a sample Java application.

本快速入门假设你已创建了 IoT 中心和设备预配服务实例。This quickstart expects you have already created an IoT hub and Device Provisioning Service instance. 如果尚未创建这些资源,请先完成使用 Azure 门户设置 IoT 中心设备预配服务快速入门,然后再继续学习本文。If you have not already created these resources, complete the Set up IoT Hub Device Provisioning Service with the Azure portal quickstart before proceeding with this article.

虽然 Java 服务 SDK 在 Windows 和 Linux 计算机上均适用,但本文使用 Windows 开发计算机来演示注册过程。Although the Java Service SDK works on both Windows and Linux machines, this article uses a Windows development machine to walk through the enrollment process.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

下载并修改 Java 示例代码Download and modify the Java sample code

本部分中将使用自签名 X.509 证书,请务必记住以下要点:This section uses a self-signed X.509 certificate, it is important to keep in mind the following points:

  • 自签名证书仅用于测试,不应在生产环境中使用。Self-signed certificates are for testing only, and should not be used in production.
  • 自签名证书的默认过期日期为一年。The default expiration date for a self-signed certificate is one year.

下面的步骤展示了如何向示例代码添加 X.509 设备的预配详细信息。The following steps show how to add the provisioning details of your X.509 device to the sample code.

  1. 打开命令提示符。Open a command prompt. 使用 Java 服务 SDK 克隆设备注册代码示例的 GitHub 存储库:Clone the GitHub repo for device enrollment code sample using the Java Service SDK:

    git clone https://github.com/Azure/azure-iot-sdk-java.git --recursive
    
  2. 在下载的源代码中,导航到示例文件夹 azure-iot-sdk-java/provisioning/provisioning-samples/service-enrollment-group-sampleIn the downloaded source code, navigate to the sample folder azure-iot-sdk-java/provisioning/provisioning-samples/service-enrollment-group-sample. 在所选编辑器中打开文件 ** /src/main/java/samples/com/microsoft/azure/sdk/iot/ServiceEnrollmentGroupSample.java** ,添加以下详细信息:Open the file /src/main/java/samples/com/microsoft/azure/sdk/iot/ServiceEnrollmentGroupSample.java in an editor of your choice, and add the following details:

    1. 在门户中为预配服务添加 [Provisioning Connection String],如下所示:Add the [Provisioning Connection String] for your provisioning service, from the portal as following:

      1. Azure 门户中导航到预配服务。Navigate to your provisioning service in the Azure portal.

      2. 打开“共享访问策略”,选择具有 EnrollmentWrite 权限的策略。Open the Shared access policies, and select a policy, which has the EnrollmentWrite permission.

      3. 复制“主密钥连接字符串”。Copy the Primary key connection string.

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

      4. 在示例代码文件 ServiceEnrollmentGroupSample.java 中,将 [Provisioning Connection String] 替换为“主密钥连接字符串”。In the sample code file ServiceEnrollmentGroupSample.java, replace the [Provisioning Connection String] with the Primary key connection string.

        private static final String PROVISIONING_CONNECTION_STRING = "[Provisioning Connection String]";
        
    2. 添加此组设备的根证书。Add the root certificate for the group of devices. 如需示例根证书,请使用 _X.509 证书生成器_工具,如下所示:If you need a sample root certificate, use the X.509 certificate generator tool as follows:

      1. 在命令窗口中,导航到文件夹 azure-iot-sdk-java/provisioning/provisioning-tools/provisioning-x509-cert-generatorIn a command window, navigate to the folder azure-iot-sdk-java/provisioning/provisioning-tools/provisioning-x509-cert-generator.
      2. 通过运行以下命令来生成工具:Build the tool by running the following command:
      mvn clean install
      
      1. 使用以下命令来运行工具:Run the tool using the following commands:
      cd target
      java -jar ./provisioning-x509-cert-generator-{version}-with-deps.jar
      
      1. 出现提示时,可以选择性地为证书输入“公用名称”。When prompted, you may optionally enter a Common Name for your certificates.
      2. 此工具在本地生成“客户端证书”、“客户端证书私钥”和“根证书”。The tool locally generates a Client Cert, the Client Cert Private Key, and the Root Cert.
      3. 复制“根证书”, 包括 ** -----BEGIN CERTIFICATE----- ** 行和 ** -----END CERTIFICATE----- ** 行。Copy the Root Cert, including the lines -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----.
      4. 将“根证书”的值指定给参数 PUBLIC_KEY_CERTIFICATE_STRING,如下所示:Assign the value of the Root Cert to the parameter PUBLIC_KEY_CERTIFICATE_STRING as shown below:
      private static final String PUBLIC_KEY_CERTIFICATE_STRING =
              "-----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";
      
      1. 关闭命令窗口,或者在系统提示输入“验证码”时输入 。Close the command window, or enter n when prompted for Verification Code.
    3. 也可选择通过示例代码配置预配服务:Optionally, you may configure your provisioning service through the sample code:

      • 若要将此配置添加到示例,请执行以下步骤:To add this configuration to the sample, follow these steps:

        1. Azure 门户中导航到已链接到预配服务的 IoT 中心。Navigate to the IoT hub linked to your provisioning service in the Azure portal. 打开中心的“概览”选项卡,复制“主机名”。Open the Overview tab for the hub, and copy the Hostname. 将该“主机名”指定给 IOTHUB_HOST_NAME 参数。Assign this Hostname to the IOTHUB_HOST_NAME parameter.

          private static final String IOTHUB_HOST_NAME = "[Host name].azure-devices.net";
          
        2. DEVICE_ID 参数指定一个友好名称,并保留 PROVISIONING_STATUS 的默认值 ENABLEDAssign a friendly name to the DEVICE_ID parameter, and keep the PROVISIONING_STATUS as the default ENABLED value.

      • 或者,如果选择不配置预配服务,请确保注释掉或删除 ServiceEnrollmentGroupSample.java 文件中的以下语句:OR, if you choose not to configure your provisioning service, make sure to comment out or delete the following statements in the ServiceEnrollmentGroupSample.java file:

        enrollmentGroup.setIotHubHostName(IOTHUB_HOST_NAME);                // Optional parameter.
        enrollmentGroup.setProvisioningStatus(ProvisioningStatus.ENABLED);  // Optional parameter.
        
    4. 研究示例代码。Study the sample code. 此代码用于创建、更新、查询和删除 X.509 设备的组注册。It creates, updates, queries, and deletes a group enrollment for X.509 devices. 若要验证是否已在门户中成功注册,请暂时性地注释掉 ServiceEnrollmentGroupSample.java 文件末尾的以下代码行:To verify successful enrollment in portal, temporarily comment out the following lines of code at the end of the ServiceEnrollmentGroupSample.java file:

      // ************************************** Delete info of enrollmentGroup ***************************************
      System.out.println("\nDelete the enrollmentGroup...");
      provisioningServiceClient.deleteEnrollmentGroup(enrollmentGroupId);
      
    5. 保存 ServiceEnrollmentGroupSample.java 文件。Save the file ServiceEnrollmentGroupSample.java.

生成并运行示例组注册Build and run sample group enrollment

  1. 打开命令窗口,导航到文件夹 azure-iot-sdk-java/provisioning/provisioning-samples/service-enrollment-group-sampleOpen a command window, and navigate to the folder azure-iot-sdk-java/provisioning/provisioning-samples/service-enrollment-group-sample.

  2. 使用以下命令生成示例代码:Build the sample code by using this command:

    mvn install -DskipTests
    

    此命令将 Maven 包 com.microsoft.azure.sdk.iot.provisioning.service 下载到计算机。This command downloads the Maven package com.microsoft.azure.sdk.iot.provisioning.service to your machine. 此包包括示例代码需要生成的适用于 Java 服务 SDK 的二进制文件。This package includes the binaries for the Java service SDK, that the sample code needs to build. 如果在上一部分运行了 _X.509 证书生成器_工具,则此包已下载到计算机上。If you ran the X.509 certificate generator tool in the preceding section, this package will be already downloaded on your machine.

  3. 运行示例,方法是在命令窗口使用以下命令:Run the sample by using these commands at the command window:

    cd target
    java -jar ./service-enrollment-group-sample-{version}-with-deps.jar
    
  4. 在成功注册后观察输出窗口。Observe the output window for successful enrollment.

  5. 在 Azure 门户中导航到预配服务。Navigate to your provisioning service in the Azure portal. 单击“管理注册”。Click Manage enrollments. 请注意,X.509 设备组显示在“注册组”选项卡下,带有自动生成的“组名称”。Notice that your group of X.509 devices appears under the Enrollment Groups tab, with an autogenerated GROUP NAME.

    验证是否已在门户中成功注册 X.509

注册单个 X.509 设备所需的修改Modifications to enroll a single X.509 device

若要注册单个 X.509 设备,请修改使用 Java 服务 SDK 将 TPM 设备注册到 IoT 中心设备预配服务一文中使用的单个注册示例代码,如下所示:To enroll a single X.509 device, modify the individual enrollment sample code used in Enroll TPM device to IoT Hub Device Provisioning Service using Java service SDK as follows:

  1. 将 X.509 客户端证书的“公用名称”复制到剪贴板。Copy the Common Name of your X.509 client certificate to the clipboard. 如果希望使用上一示例代码部分所示的 X.509 证书生成器工具,请输入证书的“公用名称”,或者使用默认的 microsoftriotcoreIf you wish to use the X.509 certificate generator tool as shown in the preceding sample code section, either enter a Common Name for your certificate, or use the default microsoftriotcore. 将该“公用名称”用作 REGISTRATION_ID 变量的值。Use this Common Name as the value for the REGISTRATION_ID variable.

    // Use common name of your X.509 client certificate
    private static final String REGISTRATION_ID = "[RegistrationId]";
    
  2. 将变量 TPM_ENDORSEMENT_KEY 重命名为 PUBLIC_KEY_CERTIFICATE_STRINGRename the variable TPM_ENDORSEMENT_KEY as PUBLIC_KEY_CERTIFICATE_STRING. 复制你的客户端证书或者“X.509 证书生成器”工具的输出中的“客户端证书”,作为 PUBLIC_KEY_CERTIFICATE_STRING 变量的值。Copy your client certificate or the Client Cert from the output of the X.509 certificate generator tool, as the value for the PUBLIC_KEY_CERTIFICATE_STRING variable.

    // Rename the variable *TPM_ENDORSEMENT_KEY* as *PUBLIC_KEY_CERTIFICATE_STRING*
    private static final String PUBLIC_KEY_CERTIFICATE_STRING =
            "-----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";
    
  3. main 函数中,将 Attestation attestation = new TpmAttestation(TPM_ENDORSEMENT_KEY); 行替换为以下内容,以便使用 X.509 客户端证书:In the main function, replace the line Attestation attestation = new TpmAttestation(TPM_ENDORSEMENT_KEY); with the following to use the X.509 client certificate:

    Attestation attestation = X509Attestation.createFromClientCertificates(PUBLIC_KEY_CERTIFICATE_STRING);
    
  4. 使用生成并运行个人注册的示例代码部分的步骤保存、生成和运行个人注册示例文件。Save, build, and run the individual enrollment sample file, using the steps in the section Build and run the sample code for individual enrollment.

清理资源Clean up resources

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

  1. 关闭计算机上的 Java 示例输出窗口。Close the Java sample output window on your machine.
  2. 关闭计算机上的“X509 证书生成器”窗口。Close the X509 Cert Generator window on your machine.
  3. 在 Azure 门户中导航到设备预配服务,单击“管理注册”,然后选择“注册组”选项卡。选择通过本快速入门注册的 X.509 设备的“组名称”,然后单击边栏选项卡顶部的“删除”按钮。Navigate to your Device Provisioning service in the Azure portal, click Manage enrollments, and then select the Enrollment Groups tab. Select the GROUP NAME for the X.509 devices you enrolled using this Quickstart, and click the Delete button at the top of the blade.

后续步骤Next steps

在本快速入门中,你将模拟的 X.509 设备组注册到了设备预配服务。In this Quickstart, you enrolled a simulated group of X.509 devices to your 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.