控制对 IoT 中心的访问Control access to IoT Hub

本文介绍用于保护 IoT 中心的选项。This article describes the options for securing your IoT hub. IoT 中心使用 权限 向每个 IoT 中心终结点授予访问权限。IoT Hub uses permissions to grant access to each IoT hub endpoint. 权限可根据功能限制对 IoT 中心的访问。Permissions limit the access to an IoT hub based on functionality.

本文介绍了以下内容:This article introduces:

  • 可以向要访问 IoT 中心的设备或后端应用授予的不同权限。The different permissions that you can grant to a device or back-end app to access your IoT hub.
  • 身份验证过程以及它用于验证权限的令牌。The authentication process and the tokens it uses to verify permissions.
  • 如何限定凭据的作用域,以限制对特定资源的访问。How to scope credentials to limit access to specific resources.
  • IoT 中心支持 X.509 证书。IoT Hub support for X.509 certificates.
  • 使用现有的设备标识注册表或身份验证方案的自定义设备身份验证机制。Custom device authentication mechanisms that use existing device identity registries or authentication schemes.

Note

本文中提到的某些功能(例如云到设备消息传递、设备孪生、设备管理)仅在 IoT 中心的标准层中提供。Some of the features mentioned in this article, like cloud-to-device messaging, device twins, and device management, are only available in the standard tier of IoT hub. 有关基本和标准 IoT 中心层的详细信息,请参阅如何选择合适的 IoT 中心层For more information about the basic and standard IoT Hub tiers, see How to choose the right IoT Hub tier.

必须具有适当的权限,才能访问任何 IoT 中心终结点。You must have appropriate permissions to access any of the IoT Hub endpoints. 例如,设备必须随它发送到 IoT 中心的每条消息提供包含安全凭据的令牌。For example, a device must include a token containing security credentials along with every message it sends to IoT Hub.

访问控制和权限Access control and permissions

可以通过以下方式授予 权限You can grant permissions in the following ways:

  • IoT 中心级别的共享访问策略IoT hub-level shared access policies. 共享访问策略可以授予任意权限组合。Shared access policies can grant any combination of permissions. 可使用 IoT 中心资源 REST API 或使用 az iot 中心策略 CLI 以编程方式在 Azure 门户中定义策略。You can define policies in the Azure portal, programmatically by using the IoT Hub Resource REST APIs, or using the az iot hub policy CLI. 新建的 IoT 中心有以下默认策略:A newly created IoT hub has the following default policies:

    共享访问策略Shared Access Policy 权限Permissions
    iothubowneriothubowner 所有权限All permission
    服务service ServiceConnect 权限ServiceConnect permissions
    设备device DeviceConnect 权限DeviceConnect permissions
    registryReadregistryRead RegistryRead 权限RegistryRead permissions
    registryReadWriteregistryReadWrite RegistryReadRegistryWrite 权限RegistryRead and RegistryWrite permissions
  • 每个设备的安全凭据Per-Device Security Credentials. 每个 IoT 中心都包含一个标识注册表。对于此标识注册表中的每个设备,可配置安全凭据,授予局限于相应设备终结点的 DeviceConnect 权限。Each IoT Hub contains an identity registry For each device in this identity registry, you can configure security credentials that grant DeviceConnect permissions scoped to the corresponding device endpoints.

例如,在典型的 IoT 解决方案中:For example, in a typical IoT solution:

  • 设备管理组件使用 registryReadWrite 策略。The device management component uses the registryReadWrite policy.
  • 事件处理器组件使用 service 策略。The event processor component uses the service policy.
  • 运行时设备业务逻辑组件使用 service 策略。The run-time device business logic component uses the service policy.
  • 各个设备的连接使用 IoT 中心的标识注册表中存储的凭据。Individual devices connect using credentials stored in the IoT hub's identity registry.

Note

有关详细信息,请参阅权限See permissions for detailed information.

身份验证Authentication

Azure IoT 中心可根据共享访问策略和标识注册表安全凭据验证令牌,进而授予终结点的访问权限。Azure IoT Hub grants access to endpoints by verifying a token against the shared access policies and identity registry security credentials.

安全凭据(例如对称密钥)永远不会通过网络发送。Security credentials, such as symmetric keys, are never sent over the wire.

Note

如同 Azure Resource Manager 中的所有提供程序一样,Azure IoT 中心资源提供程序也通过 Azure 订阅受到保护。The Azure IoT Hub resource provider is secured through your Azure subscription, as are all providers in the Azure Resource Manager.

有关如何构造和使用安全令牌的详细信息,请参阅 IoT 中心安全令牌For more information about how to construct and use security tokens, see IoT Hub security tokens.

协议详情Protocol specifics

每个支持的协议(如 MQTT、AMQP 和 HTTPS)以不同方式传输令牌。Each supported protocol, such as MQTT, AMQP, and HTTPS, transports tokens in different ways.

使用 MQTT 时,CONNECT 数据包具有用作 ClientId 的 deviceId,在 Username 字段中具有 {iothubhostname}/{deviceId},在 Password 字段中具有 SAS 令牌。When using MQTT, the CONNECT packet has the deviceId as the ClientId, {iothubhostname}/{deviceId} in the Username field, and a SAS token in the Password field. {iothubhostname} 应该是 IoT 中心的完整 CName(例如,contoso.azure-devices.cn)。{iothubhostname} should be the full CName of the IoT hub (for example, contoso.azure-devices.cn).

使用 AMQP 时,IoT 中心支持 SASL PLAINAMQP 基于声明的安全性When using AMQP, IoT Hub supports SASL PLAIN and AMQP Claims-Based-Security.

如果使用 AMQP 基于声明的安全性,该标准指定如何传输这些令牌。If you use AMQP claims-based-security, the standard specifies how to transmit these tokens.

对于 SASL PLAIN, 用户名 可以是:For SASL PLAIN, the username can be:

  • {policyName}@sas.root.{iothubName} (若使用 IoT 中心级别的令牌)。{policyName}@sas.root.{iothubName} if using IoT hub-level tokens.
  • {deviceId}@sas.{iothubname} (若为设备范围的令牌)。{deviceId}@sas.{iothubname} if using device-scoped tokens.

在这两种情况下,密码字段都包含令牌,如 IoT Hub security tokens(IoT 中心安全令牌)中所述。In both cases, the password field contains the token, as described in IoT Hub security tokens.

HTTPS 通过在 Authorization 请求标头中包含有效的令牌来实施身份验证。HTTPS implements authentication by including a valid token in the Authorization request header.

示例Example

用户名(DeviceId 区分大小写):iothubname.azure-devices.net/DeviceIdUsername (DeviceId is case-sensitive): iothubname.azure-devices.net/DeviceId

密码(可使用设备资源管理器工具、CLI 扩展命令 az iot hub generate-sas-token用于 Visual Studio Code 的 Azure IoT 工具来生成 SAS 令牌):Password (You can generate a SAS token with the device explorer tool, the CLI extension command az iot hub generate-sas-token, or the Azure IoT Tools for Visual Studio Code):

SharedAccessSignature sr=iothubname.azure-devices.net%2fdevices%2fDeviceId&sig=kPszxZZZZZZZZZZZZZZZZZAhLT%2bV7o%3d&se=1487709501

Note

Azure IoT SDK 在连接到服务时自动生成令牌。The Azure IoT SDKs automatically generate tokens when connecting to the service. 某些情况下,Azure IoT SDK 不支持部分协议或身份验证方法。In some cases, the Azure IoT SDKs do not support all the protocols or all the authentication methods.

有关 SASL PLAIN 的特殊注意事项Special considerations for SASL PLAIN

将 SASL PLAIN 用于 AMQP 时,连接到 IoT 中心的客户端可为每个 TCP 连接使用单个令牌。When using SASL PLAIN with AMQP, a client connecting to an IoT hub can use a single token for each TCP connection. 当令牌过期时,TCP 连接将与服务断开连接,并触发重新连接。When the token expires, the TCP connection disconnects from the service and triggers a reconnection. 此行为虽然不会对后端应用造成问题,但对设备应用不利,原因如下:This behavior, while not problematic for a back-end app, is damaging for a device app for the following reasons:

  • 网关通常代表许多设备连接。Gateways usually connect on behalf of many devices. 使用 SASL PLAIN 时,它们必须针对连接到 IoT 中心的每个设备创建不同的 TCP 连接。When using SASL PLAIN, they have to create a distinct TCP connection for each device connecting to an IoT hub. 此方案会大幅提高电源与网络资源的消耗并增大每个设备连接的延迟。This scenario considerably increases the consumption of power and networking resources, and increases the latency of each device connection.
  • 在每个令牌过期后,增加使用要重新连接的资源通常会对资源受限的设备造成不良影响。Resource-constrained devices are adversely affected by the increased use of resources to reconnect after each token expiration.

设置 IoT 中心级凭据的范围Scope IoT hub-level credentials

可通过使用受限资源 URI 创建令牌,设置 IoT 中心级安全策略的范围。You can scope IoT hub-level security policies by creating tokens with a restricted resource URI. 例如,要从设备发送从设备到云的消息的终结点是 /devices/{deviceId}/messages/eventsFor example, the endpoint to send device-to-cloud messages from a device is /devices/{deviceId}/messages/events. 还可以使用包含 DeviceConnect 权限的 IoT 中心级别共享访问策略对 resourceURI 为 /devices/{deviceId} 的令牌进行签名。You can also use an IoT hub-level shared access policy with DeviceConnect permissions to sign a token whose resourceURI is /devices/{deviceId}. 此方法会创建一个令牌,该令牌仅可用于代表设备 deviceId 发送消息。This approach creates a token that is only usable to send messages on behalf of device deviceId.

此机制类似于事件中心发布者策略,可用于实施自定义身份验证方法。This mechanism is similar to the Event Hubs publisher policy, and enables you to implement custom authentication methods.

安全令牌Security tokens

IoT 中心使用安全令牌对设备和服务进行身份验证,以避免在线发送密钥。IoT Hub uses security tokens to authenticate devices and services to avoid sending keys on the wire. 并且安全令牌的有效期和范围有限。Additionally, security tokens are limited in time validity and scope. Azure IoT SDK 无需任何特殊配置即可自动生成令牌。Azure IoT SDKs automatically generate tokens without requiring any special configuration. 在某些情况下,确实需要用户生成并直接使用安全令牌。Some scenarios do require you to generate and use security tokens directly. 这些情况包括:Such scenarios include:

IoT 中心还允许设备使用 X.509 证书向 IoT 中心进行身份验证。IoT Hub also allows devices to authenticate with IoT Hub using X.509 certificates.

安全令牌结构Security token structure

可以使用安全令牌向设备和服务授予限时访问 IoT 中心特定功能的权限。You use security tokens to grant time-bounded access to devices and services to specific functionality in IoT Hub. 若要获取授权连接到 IoT 中心,设备和服务必须发送使用共享访问或对称密钥进行签名的安全令牌。To get authorization to connect to IoT Hub, devices and services must send security tokens signed with either a shared access or symmetric key. 这些密钥与设备标识一起存储在标识注册表中。These keys are stored with a device identity in the identity registry.

使用共享访问密钥进行签名的令牌可授权访问与共享访问策略权限相关的所有功能。A token signed with a shared access key grants access to all the functionality associated with the shared access policy permissions. 使用设备标识的对称密钥进行签名的令牌只能向相关设备标识授予 DeviceConnect 权限。A token signed with a device identity's symmetric key only grants the DeviceConnect permission for the associated device identity.

安全令牌采用以下格式:The security token has the following format:

SharedAccessSignature sig={signature-string}&se={expiry}&skn={policyName}&sr={URL-encoded-resourceURI}

以下是预期值:Here are the expected values:

Value 说明Description
{signature}{signature} HMAC-SHA256 签名字符串的格式为: {URL-encoded-resourceURI} + "\n" + expiryAn HMAC-SHA256 signature string of the form: {URL-encoded-resourceURI} + "\n" + expiry. 重要说明:密钥是从 base64 解码得出的,用作执行 HMAC-SHA256 计算的密钥。Important: The key is decoded from base64 and used as key to perform the HMAC-SHA256 computation.
{resourceURI}{resourceURI} 使用此令牌可以访问的终结点的 URI 前缀(根据分段)以 IoT 中心的主机名开头(无协议)。URI prefix (by segment) of the endpoints that can be accessed with this token, starting with host name of the IoT hub (no protocol). 例如 myHub.azure-devices.cn/devices/device1For example, myHub.azure-devices.cn/devices/device1
{expiry}{expiry} 从纪元 1970 年 1 月 1日 00:00:00 UTC 时间至今秒数的 UTF8 字符串。UTF8 strings for number of seconds since the epoch 00:00:00 UTC on 1 January 1970.
{URL-encoded-resourceURI}{URL-encoded-resourceURI} 小写资源 URI 的小写 URL 编码Lower case URL-encoding of the lower case resource URI
{policyName}{policyName} 此令牌所引用的共享访问策略名称。The name of the shared access policy to which this token refers. 如果此令牌引用设备注册表凭据,则空缺。Absent if the token refers to device-registry credentials.

有关前缀的说明:URI 前缀是按分段而不是按字符计算的。Note on prefix: The URI prefix is computed by segment and not by character. 例如,/a/b/a/b/c 的前缀,而不是 /a/bc 的前缀。For example /a/b is a prefix for /a/b/c but not for /a/bc.

以下 Node.js 代码片段显示名为 generateSasToken 的函数,该函数通过输入 resourceUri, signingKey, policyName, expiresInMins 计算令牌。The following Node.js snippet shows a function called generateSasToken that computes the token from the inputs resourceUri, signingKey, policyName, expiresInMins. 以下各节将详细讲解如何初始化不同令牌用例的不同输入。The next sections detail how to initialize the different inputs for the different token use cases.

var generateSasToken = function(resourceUri, signingKey, policyName, expiresInMins) {
    resourceUri = encodeURIComponent(resourceUri);

    // Set expiration in seconds
    var expires = (Date.now() / 1000) + expiresInMins * 60;
    expires = Math.ceil(expires);
    var toSign = resourceUri + '\n' + expires;

    // Use crypto
    var hmac = crypto.createHmac('sha256', new Buffer(signingKey, 'base64'));
    hmac.update(toSign);
    var base64UriEncoded = encodeURIComponent(hmac.digest('base64'));

    // Construct authorization string
    var token = "SharedAccessSignature sr=" + resourceUri + "&sig="
    + base64UriEncoded + "&se=" + expires;
    if (policyName) token += "&skn="+policyName;
    return token;
};

作为对照,用于生成安全令牌的等效 Python 代码是:As a comparison, the equivalent Python code to generate a security token is:

from base64 import b64encode, b64decode
from hashlib import sha256
from time import time
from urllib import quote_plus, urlencode
from hmac import HMAC

def generate_sas_token(uri, key, policy_name, expiry=3600):
    ttl = time() + expiry
    sign_key = "%s\n%d" % ((quote_plus(uri)), int(ttl))
    print sign_key
    signature = b64encode(HMAC(b64decode(key), sign_key, sha256).digest())

    rawtoken = {
        'sr' :  uri,
        'sig': signature,
        'se' : str(int(ttl))
    }

    if policy_name is not None:
        rawtoken['skn'] = policy_name

    return 'SharedAccessSignature ' + urlencode(rawtoken)

C# 中用于生成安全令牌的功能是:The functionality in C# to generate a security token is:

using System;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

public static string generateSasToken(string resourceUri, string key, string policyName, int expiryInSeconds = 3600)
{
    TimeSpan fromEpochStart = DateTime.UtcNow - new DateTime(1970, 1, 1);
    string expiry = Convert.ToString((int)fromEpochStart.TotalSeconds + expiryInSeconds);

    string stringToSign = WebUtility.UrlEncode(resourceUri) + "\n" + expiry;

    HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));
    string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

    string token = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", WebUtility.UrlEncode(resourceUri), WebUtility.UrlEncode(signature), expiry);

    if (!String.IsNullOrEmpty(policyName))
    {
        token += "&skn=" + policyName;
    }

    return token;
}

Note

由于 IoT 中心计算机会验证令牌的有效期,因此生成令牌的计算机的时间偏差必须很小。Since the time validity of the token is validated on IoT Hub machines, the drift on the clock of the machine that generates the token must be minimal.

在设备应用中使用 SAS 令牌Use SAS tokens in a device app

有两种方法可以使用安全令牌来获取 IoT 中心的 DeviceConnect 权限:使用标识注册表中的对称设备密钥,或者使用共享访问密钥There are two ways to obtain DeviceConnect permissions with IoT Hub with security tokens: use a symmetric device key from the identity registry, or use a shared access key.

请记住,可从设备访问的所有功能都故意显示在前缀为 /devices/{deviceId} 的终结点上。Remember that all functionality accessible from devices is exposed by design on endpoints with prefix /devices/{deviceId}.

Important

IoT 中心对某个特定设备进行身份验证的唯一方法是使用设备标识对称密钥。The only way that IoT Hub authenticates a specific device is using the device identity symmetric key. 使用共享访问策略访问设备功能时,解决方案必须考虑将安全令牌作为受信任的子组件进行颁发的组件。In cases when a shared access policy is used to access device functionality, the solution must consider the component issuing the security token as a trusted subcomponent.

面向设备的终结点包括(无论任何协议):The device-facing endpoints are (irrespective of the protocol):

终结点Endpoint 功能Functionality
{iot hub host name}/devices/{deviceId}/messages/events 发送设备到云的消息。Send device-to-cloud messages.
{iot hub host name}/devices/{deviceId}/messages/devicebound 接收云到设备的消息。Receive cloud-to-device messages.

使用标识注册表中的对称密钥Use a symmetric key in the identity registry

使用设备标识的对称密钥生成令牌时,将省略令牌的 policyName (skn) 元素。When using a device identity's symmetric key to generate a token, the policyName (skn) element of the token is omitted.

例如,创建的用于访问所有设备功能的令牌应具有以下参数:For example, a token created to access all device functionality should have the following parameters:

  • 资源 URI: {IoT hub name}.azure-devices.cn/devices/{device id}resource URI: {IoT hub name}.azure-devices.cn/devices/{device id},
  • 签名密钥: {device id} 标识的任何对称密钥,signing key: any symmetric key for the {device id} identity,
  • 无策略名称;no policy name,
  • 任何过期时间。any expiration time.

上述 Node js 函数的使用示例如下:An example using the preceding Node.js function would be:

var endpoint ="myhub.azure-devices.cn/devices/device1";
var deviceKey ="...";

var token = generateSasToken(endpoint, deviceKey, null, 60);

授权访问设备 1 的所有功能的安全令牌是:The result, which grants access to all functionality for device1, would be:

SharedAccessSignature sr=myhub.azure-devices.cn%2fdevices%2fdevice1&sig=13y8ejUk2z7PLmvtwR5RqlGBOVwiq7rQR3WZ5xZX3N4%3D&se=1456971697

Note

可使用设备资源管理器工具、CLI 扩展命令 az iot hub generate-sas-token用于 Visual Studio Code 的 Azure IoT 工具来生成 SAS 令牌。It's possible to generate a SAS token with the device explorer tool, the CLI extension command az iot hub generate-sas-token, or the Azure IoT Tools for Visual Studio Code.

使用共享访问策略Use a shared access policy

使用共享访问策略创建令牌时,将 skn 字段设置为策略名称。When you create a token from a shared access policy, set the skn field to the name of the policy. 此策略必须授予 DeviceConnect 权限。This policy must grant the DeviceConnect permission.

使用共享访问策略访问设备功能的两个主要方案是:The two main scenarios for using shared access policies to access device functionality are:

由于共享访问策略可潜在授权访问任何连接设备的权限,因此创建安全令牌时必须使用正确的资源 URI。Since the shared access policy can potentially grant access to connect as any device, it is important to use the correct resource URI when creating security tokens. 这对令牌服务尤其重要,它必须使用资源 URI 将令牌的范围限定到特定设备。This setting is especially important for token services, which have to scope the token to a specific device using the resource URI. 这一点与协议网关的关系不大,因为协议网关是对所有设备的通信进行调节。This point is less relevant for protocol gateways as they are already mediating traffic for all devices.

例如,使用名为 device 的预创建共享访问策略的令牌服务会使用以下参数创建令牌:As an example, a token service using the pre-created shared access policy called device would create a token with the following parameters:

  • 资源 URI: {IoT hub name}.azure-devices.cn/devices/{device id}resource URI: {IoT hub name}.azure-devices.cn/devices/{device id},
  • 签名密钥: device 策略的密钥之一,signing key: one of the keys of the device policy,
  • 策略名称: devicepolicy name: device,
  • 任何过期时间。any expiration time.

上述 Node js 函数的使用示例如下:An example using the preceding Node.js function would be:

var endpoint ="myhub.azure-devices.cn/devices/device1";
var policyName = 'device';
var policyKey = '...';

var token = generateSasToken(endpoint, policyKey, policyName, 60);

授权访问设备 1 的所有功能的安全令牌是:The result, which grants access to all functionality for device1, would be:

SharedAccessSignature sr=myhub.azure-devices.cn%2fdevices%2fdevice1&sig=13y8ejUk2z7PLmvtwR5RqlGBOVwiq7rQR3WZ5xZX3N4%3D&se=1456971697&skn=device

协议网关可以对所有设备使用相同的令牌,只需将资源 URI 设置为 myhub.azure-devices.cn/devicesA protocol gateway could use the same token for all devices simply setting the resource URI to myhub.azure-devices.cn/devices.

使用服务组件提供的安全令牌Use security tokens from service components

如前所述,服务组件使用共享访问策略只能生成安全令牌,授予适当权限。Service components can only generate security tokens using shared access policies granting the appropriate permissions as explained previously.

以下是终结点上显示的服务功能:Here are the service functions exposed on the endpoints:

终结点Endpoint 功能Functionality
{iot hub host name}/devices 创建、更新、检索和删除设备标识。Create, update, retrieve, and delete device identities.
{iot hub host name}/messages/events 接收设备到云的消息Receive device-to-cloud messages.
{iot hub host name}/servicebound/feedback 接收云到设备的消息的反馈。Receive feedback for cloud-to-device messages.
{iot hub host name}/devicebound 发送云到设备的消息。Send cloud-to-device messages.

例如,使用名为 registryRead 的预创建共享访问策略生成的服务会使用以下参数创建令牌:As an example, a service generating using the pre-created shared access policy called registryRead would create a token with the following parameters:

  • 资源 URI: {IoT hub name}.azure-devices.cn/devicesresource URI: {IoT hub name}.azure-devices.cn/devices,
  • 签名密钥: registryRead 策略的密钥之一,signing key: one of the keys of the registryRead policy,
  • 策略名称: registryReadpolicy name: registryRead,
  • 任何过期时间。any expiration time.
    var endpoint ="myhub.azure-devices.cn/devices";
    var policyName = 'registryRead';
    var policyKey = '...';

    var token = generateSasToken(endpoint, policyKey, policyName, 60);

授权读取所有设备标识权限的安全令牌是:The result, which would grant access to read all device identities, would be:

SharedAccessSignature sr=myhub.azure-devices.cn%2fdevices&sig=JdyscqTpXdEJs49elIUCcohw2DlFDR3zfH5KqGJo4r4%3D&se=1456973447&skn=registryRead

支持的 X.509 证书Supported X.509 certificates

可以通过将证书指纹或证书颁发机构 (CA) 上传到 Azure IoT 中心,从而借助 IoT 中心使用任何 X.509 证书对设备进行身份验证。You can use any X.509 certificate to authenticate a device with IoT Hub by uploading either a certificate thumbprint or a certificate authority (CA) to Azure IoT Hub. 使用证书指纹的身份验证,仅验证提供的指纹是否与配置的指纹匹配。Authentication using certificate thumbprints only verifies that the presented thumbprint matches the configured thumbprint. 使用证书颁发机构的身份验证会验证证书链。Authentication using certificate authority validates the certificate chain.

支持的证书包括:Supported certificates include:

  • 现有的 X.509 证书An existing X.509 certificate. 设备可能已有与之关联的 X.509 证书。A device may already have an X.509 certificate associated with it. 设备可以使用此证书向 IoT 中心进行身份验证。The device can use this certificate to authenticate with IoT Hub. 适用于指纹或 CA 身份验证。Works with either thumbprint or CA authentication.
  • CA 签名的 X.509 证书CA-signed X.509 certificate. 若要识别设备并通过 IoT 中心对其进行身份验证,可使用由证书颁发机构 (CA) 生成和签名的 X.509 证书。To identify a device and authenticate it with IoT Hub, you can use an X.509 certificate generated and signed by a Certification Authority (CA). 适用于指纹或 CA 身份验证。Works with either thumbprint or CA authentication.
  • 自行生成和自签名的 X-509 证书A self-generated and self-signed X-509 certificate. 设备制造商或内部部署人员可以生成这些证书,并将相应的私钥(和证书)存储在设备上。A device manufacturer or in-house deployer can generate these certificates and store the corresponding private key (and certificate) on the device. 可以将工具(如 OpenSSLWindows SelfSignedCertificate 实用程序)用于此目的。You can use tools such as OpenSSL and Windows SelfSignedCertificate utility for this purpose. 仅适用于指纹身份验证。Only works with thumbprint authentication.

设备可以使用 X.509 证书或安全令牌进行身份验证,但不能同时使用这两者。A device may either use an X.509 certificate or a security token for authentication, but not both.

有关使用证书颁发机构进行身份验证的详细信息,请参阅使用 X.509 CA 证书进行设备身份验证For more information about authentication using certificate authority, see Device Authentication using X.509 CA Certificates.

为设备注册 X.509 证书Register an X.509 certificate for a device

用于 C# 的 Azure IoT 服务 SDK(版本 1.0.8+)支持注册使用 X.509 证书进行身份验证的设备。The Azure IoT Service SDK for C# (version 1.0.8+) supports registering a device that uses an X.509 certificate for authentication. 其他 API(例如设备的导入/导出)也支持 X.509 证书。Other APIs such as import/export of devices also support X.509 certificates.

此外,还可使用 CLI 扩展命令 az iot hub device-identity 配置设备的 X.509 证书。You can also use the CLI extension command az iot hub device-identity to configure X.509 certificates for devices.

C# 支持C# Support

RegistryManager 类提供了用于注册设备的编程方式。The RegistryManager class provides a programmatic way to register a device. 具体而言,使用 AddDeviceAsyncUpdateDeviceAsync 方法,用户可以在 IoT 中心标识注册表中注册和更新设备。In particular, the AddDeviceAsync and UpdateDeviceAsync methods enable you to register and update a device in the IoT Hub identity registry. 这两种方法均采用 Device 实例作为输入。These two methods take a Device instance as input. Device 类包括 Authentication 属性,允许用户指定主要和次要 X.509 证书指纹。The Device class includes an Authentication property that allows you to specify primary and secondary X.509 certificate thumbprints. 指纹表示 X.509 证书的 SHA256 哈希值(使用二进制 DER 编码存储)。The thumbprint represents a SHA256 hash of the X.509 certificate (stored using binary DER encoding). 用户可以选择指定主要指纹和/或次要指纹。You have the option of specifying a primary thumbprint or a secondary thumbprint or both. 为了处理证书滚动更新方案,支持主要和次要指纹。Primary and secondary thumbprints are supported to handle certificate rollover scenarios.

下面是使用 X.509 证书指纹注册设备的示例 C# 代码片段:Here is a sample C# code snippet to register a device using an X.509 certificate thumbprint:

var device = new Device(deviceId)
{
  Authentication = new AuthenticationMechanism()
  {
    X509Thumbprint = new X509Thumbprint()
    {
      PrimaryThumbprint = "B4172AB44C28F3B9E117648C6F7294978A00CDCBA34A46A1B8588B3F7D82C4F1"
    }
  }
};
RegistryManager registryManager = RegistryManager.CreateFromConnectionString(deviceGatewayConnectionString);
await registryManager.AddDeviceAsync(device);

在运行时操作期间使用 X.509 证书Use an X.509 certificate during run-time operations

用于 .NET 的 Azure IoT 设备 SDK(版本 1.0.11+)支持使用 X.509 证书。The Azure IoT device SDK for .NET (version 1.0.11+) supports the use of X.509 certificates.

C# 支持C# Support

DeviceAuthenticationWithX509Certificate 支持使用 X.509 证书创建 DeviceClient 实例。The class DeviceAuthenticationWithX509Certificate supports the creation of DeviceClient instances using an X.509 certificate. X.509 证书必须采用 PFX(也称为 PKCS #12)格式,其中包含私钥。The X.509 certificate must be in the PFX (also called PKCS #12) format that includes the private key.

下面是示例代码片段:Here is a sample code snippet:

var authMethod = new DeviceAuthenticationWithX509Certificate("<device id>", x509Certificate);

var deviceClient = DeviceClient.Create("<IotHub DNS HostName>", authMethod);

自定义设备和模块身份验证Custom device and module authentication

可以使用 IoT 中心标识注册表,通过令牌配置每个设备/模块的安全凭据和访问控制。You can use the IoT Hub identity registry to configure per-device/module security credentials and access control using tokens. 如果 IoT 解决方案已经具有自定义标识注册表和/或身份验证方案,可考虑通过创建“令牌服务”,将此基础结构与 IoT 中心集成。If an IoT solution already has a custom identity registry and/or authentication scheme, consider creating a token service to integrate this infrastructure with IoT Hub. 这样,便可以在解决方案中使用其他 IoT 功能。In this way, you can use other IoT features in your solution.

令牌服务是自定义云服务。A token service is a custom cloud service. 它使用包含 DeviceConnectModuleConnect 权限的 IoT 中心共享访问策略创建设备范围的或模块范围的令牌。It uses an IoT Hub shared access policy with DeviceConnect or ModuleConnect permissions to create device-scoped or module-scoped tokens. 这些令牌可让设备和模块连接到 IoT 中心。These tokens enable a device and module to connect to your IoT hub.

令牌服务模式的步骤

下面是令牌服务模式的主要步骤:Here are the main steps of the token service pattern:

  1. 为 IoT 中心创建包含 DeviceConnectModuleConnect 权限的 IoT 中心共享访问策略。Create an IoT Hub shared access policy with DeviceConnect or ModuleConnect permissions for your IoT hub. 可以在 Azure 门户 中或以编程方式创建此策略。You can create this policy in the Azure portal or programmatically. 令牌服务使用此策略为它创建的令牌签名。The token service uses this policy to sign the tokens it creates.
  2. 当设备/模块需要访问 IoT 中心时,将向令牌服务请求已签名的令牌。When a device/module needs to access your IoT hub, it requests a signed token from your token service. 设备/模块可以使用自定义标识注册表/身份验证方案来进行身份验证,以确定令牌服务用来创建令牌的设备/模块标识。The device can authenticate with your custom identity registry/authentication scheme to determine the device/module identity that the token service uses to create the token.
  3. 令牌服务返回令牌。The token service returns a token. 创建令牌时,使用 /devices/{deviceId}/devices/{deviceId}/module/{moduleId} 作为 resourceURI,使用 deviceId 作为要进行身份验证的设备,或者使用 moduleId 作为要进行身份验证的模块。The token is created by using /devices/{deviceId} or /devices/{deviceId}/module/{moduleId} as resourceURI, with deviceId as the device being authenticated or moduleId as the module being authenticated. 令牌服务使用共享访问策略来构造令牌。The token service uses the shared access policy to construct the token.
  4. 设备/模块直接通过 IoT 中心使用令牌。The device/module uses the token directly with the IoT hub.

Note

可以使用 .NET 类 SharedAccessSignatureBuilder 或 Java 类 IotHubServiceSasToken 在令牌服务中创建令牌。You can use the .NET class SharedAccessSignatureBuilder or the Java class IotHubServiceSasToken to create a token in your token service.

令牌服务可以根据需要设置令牌过期日期。The token service can set the token expiration as desired. 令牌过期时,IoT 中心将断开设备/模块连接。When the token expires, the IoT hub severs the device/module connection. 然后,设备/模块必须向令牌服务请求新令牌。Then, the device/module must request a new token from the token service. 到期时间过短会增加设备/模块和令牌服务上的负载。A short expiry time increases the load on both the device/module and the token service.

为了让设备/模块连接到中心,仍必须将它添加到 IoT 中心标识注册表,即使设备/模块使用令牌而不是密钥来连接。For a device/module to connect to your hub, you must still add it to the IoT Hub identity registry — even though it is using a token and not a key to connect. 因此,可通过在识别注册表中启用或禁用设备/模块标识,来继续使用基于设备/模块的访问控制。Therefore, you can continue to use per-device/per-module access control by enabling or disabling device/module identities in the identity registry. 此方法可以减轻使用较长到期时间令牌的风险。This approach mitigates the risks of using tokens with long expiry times.

与自定义网关的比较Comparison with a custom gateway

令牌服务模式是使用 IoT 中心实现自定义标识注册表/身份验证方案的建议方式。The token service pattern is the recommended way to implement a custom identity registry/authentication scheme with IoT Hub. 建议使用这种模式是因为 IoT 中心继续处理大部分解决方案流量。This pattern is recommended because IoT Hub continues to handle most of the solution traffic. 但是,如果自定义身份验证方案与协议过度交织,可能需要自定义网关来处理所有流量。However, if the custom authentication scheme is so intertwined with the protocol, you may require a custom gateway to process all the traffic. 使用传输层安全 (TLS) 和预共享密钥 (PSK) 就是这种情况的例子。An example of such a scenario is usingTransport Layer Security (TLS) and pre-shared keys (PSKs). 有关详细信息,请参阅协议网关一文。For more information, see the protocol gateway article.

参考主题:Reference topics:

以下参考主题提供有关控制对 IoT 中心的访问的详细信息。The following reference topics provide you with more information about controlling access to your IoT hub.

IoT 中心权限IoT Hub permissions

下表列出了可用于控制对 IoT 中心的访问的权限。The following table lists the permissions you can use to control access to your IoT hub.

权限Permission 注释Notes
RegistryReadRegistryRead 授予对标识注册表的读取访问权限。Grants read access to the identity registry. 有关详细信息,请参阅标识注册表For more information, see Identity registry.
后端云服务会使用此权限。This permission is used by back-end cloud services.
RegistryReadWriteRegistryReadWrite 授予对标识注册表的读取和写入访问权限。Grants read and write access to the identity registry. 有关详细信息,请参阅标识注册表For more information, see Identity registry.
后端云服务会使用此权限。This permission is used by back-end cloud services.
ServiceConnectServiceConnect 授予对面向云服务的通信和监视终结点的访问权限。Grants access to cloud service-facing communication and monitoring endpoints.
授予接收设备到云消息、发送云到设备消息和检索相应传送确认的权限。Grants permission to receive device-to-cloud messages, send cloud-to-device messages, and retrieve the corresponding delivery acknowledgments.
授予检索文件上传的传送确认的权限。Grants permission to retrieve delivery acknowledgements for file uploads.
授予访问孪生以更新标记和所需属性、检索报告属性和运行查询的权限。Grants permission to access twins to update tags and desired properties, retrieve reported properties, and run queries.
后端云服务会使用此权限。This permission is used by back-end cloud services.
DeviceConnectDeviceConnect 授予对面向设备的终结点的访问权限。Grants access to device-facing endpoints.
授予发送设备到云消息和接收云到设备消息的权限。Grants permission to send device-to-cloud messages and receive cloud-to-device messages.
授予从设备执行文件上传的权限。Grants permission to perform file upload from a device.
授予接收设备孪生所需属性通知和更新设备孪生报告属性的权限。Grants permission to receive device twin desired property notifications and update device twin reported properties.
授予执行文件上传的权限。Grants permission to perform file uploads.
此权限由设备使用。This permission is used by devices.

其他参考资料Additional reference material

IoT 中心开发人员指南中的其他参考主题包括:Other reference topics in the IoT Hub developer guide include:

  • IoT 中心终结点,介绍了每个 IoT 中心针对运行时和管理操作公开的各种终结点。IoT Hub endpoints describes the various endpoints that each IoT hub exposes for run-time and management operations.
  • 限制和配额介绍了适用于 IoT 中心服务的配额和限制行为。Throttling and quotas describes the quotas and throttling behaviors that apply to the IoT Hub service.
  • Azure IoT 设备和服务 SDK,列出了在开发与 IoT 中心交互的设备和服务应用时可使用的各种语言 SDK。Azure IoT device and service SDKs lists the various language SDKs you can use when you develop both device and service apps that interact with IoT Hub.
  • IoT 中心查询语言介绍了可用来从 IoT 中心检索设备克隆和作业相关信息的查询语言。IoT Hub query language describes the query language you can use to retrieve information from IoT Hub about your device twins and jobs.
  • IoT 中心 MQTT 支持 提供有关 IoT 中心对 MQTT 协议的支持的详细信息。IoT Hub MQTT support provides more information about IoT Hub support for the MQTT protocol.

后续步骤Next steps

既然已了解如何控制对 IoT 中心的访问,可能有兴趣了解以下 IoT 中心开发人员指南主题:Now that you have learned how to control access IoT Hub, you may be interested in the following IoT Hub developer guide topics:

如果要尝试本文中介绍的一些概念,请参阅以下 IoT 中心教程:If you would like to try out some of the concepts described in this article, see the following IoT Hub tutorials: