控制对 Azure IoT 中心设备预配服务的访问Control access to Azure IoT Hub Device Provisioning Service

本文介绍了用于保护 IoT 设备预配服务的选项。This article describes the options for securing your IoT Device Provisioning service. 预配服务使用“权限”向每个终结点授予访问权限 。The provisioning service uses permissions to grant access to each endpoint. 权限可根据功能限制对服务实例的访问。Permissions limit the access to a service instance based on functionality.

本文介绍:This article describes:

  • 可向后端应用授予的不同预配服务访问权限。The different permissions that you can grant to a backend app to access your provisioning service.
  • 身份验证过程以及它用于验证权限的令牌。The authentication process and the tokens it uses to verify permissions.

何时使用When to use

要访问某预配服务终结点,必须具有适当的权限。You must have appropriate permissions to access any of the provisioning service endpoints. 例如,后端应用必须包含一个带安全凭据的令牌,以及它发送给该服务的每条消息。For example, a backend app must include a token containing security credentials along with every message it sends to the service.

访问控制和权限Access control and permissions

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

  • 共享访问授权策略 。Shared access authorization policies. 共享访问策略可以授予任意权限组合。Shared access policies can grant any combination of permissions. 可在 Azure 门户中定义策略,也可使用设备预配服务 REST API 以编程方式进行定义。You can define policies in the Azure portal, or programmatically by using the Device Provisioning Service REST APIs. 新建的预配服务有以下默认策略:A newly created provisioning service has the following default policy:

  • provisioningserviceowner:包含所有权限的策略 。provisioningserviceowner: Policy with all permissions.

备注

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

AuthenticationAuthentication

Azure IoT 中心设备预配服务通过针对共享访问策略验证令牌,授予对终结点的访问权限。Azure IoT Hub Device Provisioning Service grants access to endpoints by verifying a token against the shared access policies. 安全凭据(例如对称密钥)永远不会通过网络发送。Security credentials, such as symmetric keys, are never sent over the wire.

备注

如同 Azure 资源管理器中的所有提供程序一样,设备预配服务资源提供程序也通过 Azure 订阅受到保护。The Device Provisioning Service resource provider is secured through your Azure subscription, as are all providers in the Azure Resource Manager.

有关如何构造和使用安全令牌的详细信息,请参阅下一部分。For more information about how to construct and use security tokens, see the next section.

HTTP 是唯一受支持的协议,它通过在“Authorization”请求标头中包含有效的令牌来实现身份验证 。HTTP is the only supported protocol, and it implements authentication by including a valid token in the Authorization request header.

示例Example

SharedAccessSignature sr = 
   mydps.azure-devices-provisioning.cn&sig=kPszxZZZZZZZZZZZZZZZZZAhLT%2bV7o%3d&se=1487709501&skn=provisioningserviceowner`\

备注

Azure IoT 设备预配服务 SDK 在连接到服务时自动生成令牌。The Azure IoT Device Provisioning Service SDKs automatically generate tokens when connecting to the service.

安全令牌Security tokens

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

安全令牌结构Security token structure

可使用安全令牌向服务授予限时访问 IoT 设备预配服务中特定功能的权限。You use security tokens to grant time-bounded access for services to specific functionality in IoT Device Provisioning Service. 要获取连接到预配服务的权限,服务必须发送使用共享访问或对称密钥进行签名的安全令牌。To get authorization to connect to the provisioning service, services must send security tokens signed with either a shared access or symmetric key.

使用共享访问密钥进行签名的令牌可以授权访问与共享访问策略权限相关的所有功能。A token signed with a shared access key grants access to all the functionality associated with the shared access policy permissions.

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

SharedAccessSignature sig={signature}&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.
{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. 此令牌可访问的终结点的 URI 前缀(按分段),以 IoT 设备预配服务的主机名开头(无协议)。URI prefix (by segment) of the endpoints that can be accessed with this token, starting with host name of the IoT Device Provisioning Service (no protocol). 例如,mydps.azure-devices-provisioning.cnFor example, mydps.azure-devices-provisioning.cn.
{policyName}{policyName} 此令牌所引用的共享访问策略名称。The name of the shared access policy to which this token refers.

有关前缀的说明: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 + "&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)),
        'skn' : policy_name
    }

    return 'SharedAccessSignature ' + urlencode(rawtoken)

备注

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

使用服务组件提供的安全令牌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
{your-service}.azure-devices-provisioning.cn/enrollments 向设备注册操作提供设备预配服务。Provides device enrollment operations with the Device Provisioning Service.
{your-service}.azure-devices-provisioning.cn/enrollmentGroups 提供用于管理设备注册组的操作。Provides operations for managing device enrollment groups.
{your-service}.azure-devices-provisioning.cn/registrations/{id} 提供用于检索和管理设备注册状态的操作。Provides operations for retrieving and managing the status of device registrations.

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

  • 资源 URI:{mydps}.azure-devices-provisioning.cnresource URI: {mydps}.azure-devices-provisioning.cn,
  • 签名密钥:enrollmentread 策略的密钥之一,signing key: one of the keys of the enrollmentread policy,
  • 策略名称:enrollmentreadpolicy name: enrollmentread,
  • 任何过期 time.backnany expiration time.backn

在门户中为设备预配服务实例创建共享访问策略

var endpoint ="mydps.azure-devices-provisioning.cn";
var policyName = 'enrollmentread'; 
var policyKey = '...';

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

授权读取所有注册记录的结果将是:The result, which would grant access to read all enrollment records, would be:

SharedAccessSignature sr=mydps.azure-devices-provisioning.cn&sig=JdyscqTpXdEJs49elIUCcohw2DlFDR3zfH5KqGJo4r4%3D&se=1456973447&skn=enrollmentread

参考主题:Reference topics:

以下参考主题详细删除如何控制对 IoT 设备预配服务的访问。The following reference topics provide you with more information about controlling access to your IoT Device Provisioning Service.

设备预配服务权限Device Provisioning Service permissions

下表列出了可用于控制对 IoT 设备预配服务的访问的权限。The following table lists the permissions you can use to control access to your IoT Device Provisioning Service.

权限Permission 说明Notes
ServiceConfig ServiceConfig 授予用于更改服务配置的访问权限。Grants access to change the service configurations.
后端云服务将使用此权限。This permission is used by backend cloud services.
EnrollmentRead EnrollmentRead 授予对设备注册和注册组的读取访问权限。Grants read access to the device enrollments and enrollment groups.
后端云服务将使用此权限。This permission is used by backend cloud services.
EnrollmentWrite EnrollmentWrite 授予对设备注册和注册组的写入访问权限。Grants write access to the device enrollments and enrollment groups.
后端云服务将使用此权限。This permission is used by backend cloud services.
RegistrationStatusRead RegistrationStatusRead 授予对设备注册状态的读取访问权限。Grants read access to the device registration status.
后端云服务将使用此权限。This permission is used by backend cloud services.
RegistrationStatusWrite RegistrationStatusWrite 授予对设备注册状态的删除访问权限。Grants delete access to the device registration status.
后端云服务将使用此权限。This permission is used by backend cloud services.