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

本快速入门展示了如何使用 C# 以编程方式创建使用中间或根 CA X.509 证书的注册组This quickstart shows how to use C# to programmatically create an Enrollment group that uses intermediate or root CA X.509 certificates. 该注册组是使用用于 .NET 的 Microsoft Azure SDK 和一个示例 C# .NET Core 应用程序创建的。The enrollment group is created by using the Microsoft Azure IoT SDK for .NET and a sample C# .NET Core application. 注册组可以控制对设备的预配服务的访问,此类设备在其证书链中共享常用签名证书。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. 若要详细了解如何将基于 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.

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

本文使用 Windows 开发计算机,不过,本文中的步骤在 Windows 和 Linux 计算机上均适用。Although the steps in this article work on both Windows and Linux computers, this article uses a Windows development computer.

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

必备条件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.

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 do proof-of-possession with the service to verify the certificate.

注意

使用 SDK 工具创建的证书只能用于开发测试。Use certificates created with the SDK tooling for development testing only. 请不要在生产环境中使用这些证书。Do not use these certificates in production. 它们包含硬编码的密码(例如 1234),在 30 天后过期。They contain hard-coded passwords, such as 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, do 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.

除了使用 C SDK 中的工具之外,用于 .NET 的 Microsoft Azure IoT SDK 中的组证书验证示例演示了如何使用现有的 X.509 中间或根 CA 证书采用 C# 执行所有权证明操作。In addition to the tooling in the C SDK, the Group certificate verification sample in the Microsoft Azure IoT SDK for .NET shows how to do proof-of-possession in C# with an existing X.509 intermediate or root CA certificate.

获取适用于预配服务的连接字符串Get the connection string for your provisioning service

对于本快速入门中的示例,需要适用于预配服务的连接字符串。For the sample in this quickstart, you need the connection string for your provisioning service.

  1. 登录到 Azure 门户,选择“所有资源”,然后选择你的设备预配服务。 Sign in to the Azure portal, select All resources, and then your Device Provisioning Service.

  2. 选择“共享访问策略”,然后选择需要用来打开其属性的访问策略。 Select Shared access policies, then choose the access policy you want to use to open its properties. 在“访问策略”中,复制并保存主密钥连接字符串。 In Access Policy, copy and save the primary key connection string.

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

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

本部分介绍如何创建一个 .NET Core 控制台应用,用于将注册组添加到预配服务。This section shows how to create a .NET Core console app that adds an enrollment group to your provisioning service. 进行一些修改后,还可以按这些步骤创建 Windows IoT Core 控制台应用,以便添加注册组。With some modification, you can also follow these steps to create a Windows IoT Core console app to add the enrollment group. 若要详细了解如何使用 IoT Core 进行开发,请参阅 Windows IoT Core developer documentation(Windows IoT Core 开发人员文档)。To learn more about developing with IoT Core, see the Windows IoT Core developer documentation.

  1. 打开 Visual Studio 并选择“创建新项目” 。Open Visual Studio and select Create a new project. 在“创建新项目”中,为 C# 项目模板选择“控制台应用(.NET Core)”,然后选择“下一步”。 In Create a new project, choose the Console App (.NET Core) for C# project template and select Next.

  2. 将项目命名为 CreateEnrollmentGroup,然后按“创建” 。Name the project CreateEnrollmentGroup, and then press Create.

    配置 Visual C# Windows 经典桌面项目

  3. 解决方案在 Visual Studio 中打开时,在“解决方案资源管理器”窗格中,右键单击“CreateEnrollmentGroup”项目,然后选择“管理 NuGet 包” 。When the solution opens in Visual Studio, in the Solution Explorer pane, right-click the CreateEnrollmentGroup project, and then select Manage NuGet Packages.

  4. 在“NuGet 包管理器”中选择“浏览”,搜索并选择“Microsoft.Azure.Devices.Provisioning.Service”,然后按“安装” 。In NuGet Package Manager, select Browse, search for and choose Microsoft.Azure.Devices.Provisioning.Service, and then press Install.

    “NuGet 包管理器”窗口

    此步骤会下载、安装 Azure IoT 预配服务客户端 SDK NuGet 包及其依赖项并添加对它的引用。This step downloads, installs, and adds a reference to the Azure IoT Provisioning Service Client SDK NuGet package and its dependencies.

  5. using 顶部的其他 using 语句之后添加以下 Program.cs 语句:Add the following using statements after the other using statements at the top of Program.cs:

    using System.Security.Cryptography.X509Certificates;
    using System.Threading.Tasks;
    using Microsoft.Azure.Devices.Provisioning.Service;
    
  6. 将以下字段添加到 Program 类,并按所列内容进行更改。Add the following fields to the Program class, and make the listed changes.

    private static string ProvisioningConnectionString = "{ProvisioningServiceConnectionString}";
    private static string EnrollmentGroupId = "enrollmentgrouptest";
    private static string X509RootCertPath = @"{Path to a .cer or .pem file for a verified root CA or intermediate CA X.509 certificate}";
    
    • ProvisioningServiceConnectionString 占位符值替换为需要为其创建注册的预配服务的连接字符串。Replace the ProvisioningServiceConnectionString placeholder value with the connection string of the provisioning service that you want to create the enrollment for.

    • X509RootCertPath 占位符值替换为 .pem 或 .cer 文件的路径。Replace the X509RootCertPath placeholder value with the path to a .pem or .cer file. 此文件代表中间或根 CA X.509 证书的公用部分,而该证书此前已通过预配服务上传和验证。This file represents the public part of an intermediate or root CA X.509 certificate that has been previously uploaded and verified with your provisioning service.

    • 可以选择性地更改 EnrollmentGroupId 值。You may optionally change the EnrollmentGroupId value. 字符串只能包含小写字符和连字符。The string can contain only lower case characters and hyphens.

    重要

    在生产代码中,请注意以下安全注意事项:In production code, be aware of the following security considerations:

    • 为预配服务管理员硬编码连接字符串不符合安全最佳做法。Hard-coding the connection string for the provisioning service administrator is against security best practices. 与硬编码相反,连接字符串应采用安全方式进行存储,例如存储在安全配置文件或注册表中。Instead, the connection string should be held in a secure manner, such as in a secure configuration file or in the registry.
    • 确保只上传签名证书的公用部分。Be sure to upload only the public part of the signing certificate. 不要将包含私钥的 .pfx (PKCS12) 或 .pem 文件上传到预配服务。Never upload .pfx (PKCS12) or .pem files containing private keys to the provisioning service.
  7. 将以下方法添加到 Program 类。Add the following method to the Program class. 此代码创建一个注册组条目,然后调用 CreateOrUpdateEnrollmentGroupAsync 中的 ProvisioningServiceClient 方法,将注册组添加到预配服务。This code creates an enrollment group entry and then calls the CreateOrUpdateEnrollmentGroupAsync method on ProvisioningServiceClient to add the enrollment group to the provisioning service.

    public static async Task RunSample()
    {
        Console.WriteLine("Starting sample...");
    
        using (ProvisioningServiceClient provisioningServiceClient =
                ProvisioningServiceClient.CreateFromConnectionString(ProvisioningConnectionString))
        {
            #region Create a new enrollmentGroup config
            Console.WriteLine("\nCreating a new enrollmentGroup...");
            var certificate = new X509Certificate2(X509RootCertPath);
            Attestation attestation = X509Attestation.CreateFromRootCertificates(certificate);
            EnrollmentGroup enrollmentGroup =
                    new EnrollmentGroup(
                            EnrollmentGroupId,
                            attestation)
                    {
                        ProvisioningStatus = ProvisioningStatus.Enabled
                    };
            Console.WriteLine(enrollmentGroup);
            #endregion
    
            #region Create the enrollmentGroup
            Console.WriteLine("\nAdding new enrollmentGroup...");
            EnrollmentGroup enrollmentGroupResult =
                await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);
            Console.WriteLine("\nEnrollmentGroup created with success.");
            Console.WriteLine(enrollmentGroupResult);
            #endregion
    
        }
    }
    
  8. 最后,将 Main 方法的主体替换为以下行:Finally, replace the body of the Main method with the following lines:

    RunSample().GetAwaiter().GetResult();
    Console.WriteLine("\nHit <Enter> to exit ...");
    Console.ReadLine();
    
  9. 生成解决方案。Build the solution.

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

运行 Visual Studio 中的示例,创建注册组。Run the sample in Visual Studio to create the enrollment group. 系统将显示命令提示符窗口并开始显示确认消息。A Command Prompt window will appear and start showing confirmation messages. 成功创建后,命令提示符窗口会显示新注册组的属性。On successful creation, the Command Prompt window displays the properties of the new enrollment group.

可以验证注册组是否已创建。You can verify that the enrollment group has been created. 转到设备预配服务的摘要,依次选择“管理注册”、“注册组”。 Go to the Device Provisioning Service summary, and select Manage enrollments, then select Enrollment Groups. 此时会看到一个新的注册条目,对应于示例中使用的注册 ID。You should see a new enrollment entry that corresponds to the registration ID you used in the sample.

门户中的注册属性

选择该条目即可验证证书指纹以及该条目的其他属性。Select the entry to verify the certificate thumbprint and other properties for the entry.

清理资源Clean up resources

如果你打算学习 C# 服务示例,请勿清理本快速入门中创建的资源。If you plan to explore the C# service sample, don't clean up the resources created in this quickstart. 否则,请使用以下步骤删除本快速入门创建的所有资源。Otherwise, use the following steps to delete all resources created by this quickstart.

  1. 关闭计算机上的 C# 示例输出窗口。Close the C# sample output window on your computer.

  2. 在 Azure 门户中导航到设备预配服务,依次选择“管理注册”、“注册组”。 Navigate to your Device Provisioning service in the Azure portal, select Manage enrollments, and then select Enrollment Groups. 选择使用本快速入门创建的注册项的“注册 ID”,然后按“删除” 。Select the Registration ID for the enrollment entry you created using this quickstart and press Delete.

  3. 在 Azure 门户上的设备预配服务中选择“证书”,选择为本快速入门上传的证书,然后按“证书详细信息”顶部的“删除” 。From your Device Provisioning service in the Azure portal, select Certificates, choose the certificate you uploaded for this quickstart, and press Delete at the top of Certificate Details.

后续步骤Next steps

在本快速入门中,你已使用 Azure IoT 中心设备预配服务为 X.509 中间或根 CA 证书创建了一个注册组。In this quickstart, you created an enrollment group 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.