

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# Authorization
<a name="iot-authorization"></a>

授权是向经过身份验证的身份授予权限的过程。您授予 AWS IoT Core 使用 AWS IoT Core 和 IAM 策略的权限。本主题介绍了 AWS IoT Core 策略。有关 IAM 策略的更多信息，请参阅 [的身份和访问管理 AWS IoT](security-iam.md) 和 [如何 AWS IoT 与 IAM 配合使用](security_iam_service-with-iam.md)。

AWS IoT Core 策略决定了经过身份验证的身份可以做什么。经身份验证的身份由设备、移动应用程序、Web 应用程序和桌面应用程序使用。经过身份验证的身份甚至可以是用户键入 AWS IoT Core CLI 命令。只有当身份拥有向其授予 AWS IoT Core 操作权限的策略时，该身份才能执行这些操作。

 AWS IoT Core 策略和 IAM 策略均 AWS IoT Core 用于控制身份（也称为*委托人*）可以执行的操作。您使用的策略类型取决于您用来进行身份验证的身份类型 AWS IoT Core。

AWS IoT Core 操作分为两组：
+ 控制面板 API 允许您执行诸如创建或更新证书、事物、规则等管理任务。
+ 数据平面 API 允许您向数据发送和接收数据 AWS IoT Core。

您使用的策略类型取决于您使用的是控制面板 API 还是数据面板 API。

下表显示了身份类型、它们使用的协议和可用于授权的策略类型。


**AWS IoT Core 数据平面 API 和策略类型**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/iot-authorization.html)


**AWS IoT Core 控制平面 API 和策略类型**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/iot-authorization.html)

AWS IoT Core 策略附加到 X.509 证书、Amazon Cognito 身份或事物组。IAM 策略附加到 IAM 用户、组或角色。如果您使用 AWS IoT 控制台或 AWS IoT Core CLI 附加策略（到证书、Amazon Cognito Identity 或事物组），则 AWS IoT Core 使用策略。否则，您将使用 IAM 策略。 AWS IoT Core 附加到事物组的策略适用于该事物组中的任何事物。要使 AWS IoT Core 策略生效，`clientId`和事物名称必须匹配。

基于策略的授权功能强大。它使您能够完全控制设备、用户或应用程序可在 AWS IoT Core中执行的操作。例如，假设使用证书连接 AWS IoT Core 的设备。您可以允许设备访问所有 MQTT 主题，也可以限制它的访问权限，只允许它访问一个主题。再举一例，假设用户在命令行中键入 CLI 命令。通过使用策略，您可以允许或拒绝用户访问任何命令或 AWS IoT Core 资源。此外，您还可以控制应用程序对 AWS IoT Core 资源的访问。

对策略所做的更改可能需要几分钟才能生效，具体取决于 AWS IoT 缓存策略文档的方式。也就是说，访问最近被授予访问权限的资源可能需要几分钟时间，并且资源可能在撤销访问权限后几分钟内仍可访问。

## AWS 培训和认证
<a name="iot-authorization-training"></a>

有关授权的信息 AWS IoT Core，请参加 AWS 培训和认证网站上的 “[深入了解 AWS IoT Core 身份验证和授权](https://www.aws.training/Details/Curriculum?id=42335)” 课程。

# AWS IoT Core 政策
<a name="iot-policies"></a>

AWS IoT Core 策略是 JSON 文档。它们遵循与 IAM 策略相同的惯例。 AWS IoT Core 支持命名策略，因此许多身份可以引用同一个策略文档。命名策略采用版本化，以便可以轻松回滚。

AWS IoT Core 策略允许您控制对 AWS IoT Core 数据平面的访问。 AWS IoT Core 数据面板由以下操作组成，允许您连接到 AWS IoT Core 消息代理，发送和接收 MQTT 消息以及获取或更新事物的 Device Shadow。

 AWS IoT Core 策略是包含一个或多个政策声明的 JSON 文档。每个语句包含：
+ `Effect`，指定是允许还是拒绝该操作。
+ `Action`，用于指定策略允许或拒绝的操作。
+ `Resource`，用于指定允许或拒绝对其执行操作的资源。

由于策略文档的 AWS IoT 缓存方式不同，对策略所做的更改可能需要 6 到 8 分钟才能生效。也就是说，访问最近被授予访问权限的资源可能需要几分钟时间，并且资源可能在撤销访问权限后几分钟内仍可访问。

AWS IoT Core 策略可以附加到 X.509 证书、Amazon Cognito 身份和事物组。附加到事物组的策略适用于该组中的任何事物。要使策略生效，`clientId` 和事物名称必须匹配。 AWS IoT Core 策略遵循与 IAM 策略相同的策略评估逻辑。默认情况下，所有策略都被隐式拒绝。任何基于身份或基于资源的策略中的显式允许将覆盖此默认行为。任何策略中的显式拒绝将覆盖任何允许。有关更多信息，请参阅《AWS Identity and Access Management 用户指南》**中的[策略评估逻辑](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow)。

**Topics**
+ [AWS IoT Core 政策行动](iot-policy-actions.md)
+ [AWS IoT Core 动作资源](iot-action-resources.md)
+ [AWS IoT Core 策略变量](iot-policy-variables.md)
+ [防止跨服务混淆座席](cross-service-confused-deputy-prevention.md)
+ [AWS IoT Core 策略示例](example-iot-policies.md)
+ [使用 Amazon Cognito Identity 的授权](cog-iot-policies.md)

# AWS IoT Core 政策行动
<a name="iot-policy-actions"></a>

 AWS IoT Core定义了以下策略操作：MQTT 策略操作

`iot:Connect`  
表示连接到 AWS IoT Core 消息代理的权限。每次向代理发送 `iot:Connect` 请求时，均检查 `CONNECT` 权限。消息代理禁止两个具有相同 ID 的客户端同时保持连接状态。在第二个客户端连接后，代理将关闭现有连接。`iot:Connect` 权限可用来确保仅使用特定客户端 ID 的授权客户端可以连接。

`iot:DeleteConnection`  
表示从 AWS IoT Core断开连接的 MQTT 客户端的权限。每次请求强制断开客户端连接时，都会检查 `iot:DeleteConnection` 权限。断开客户端连接时， AWS IoT Core 会关闭客户端的网络连接，并可选择清除会话状态。

`iot:GetRetainedMessage`  
代表获取保留单条消息内容的权限。保留的消息是在设置了 RETAIN 标志的情况下发布并由存储的消息 AWS IoT Core。有关获取账户所有保留消息列表的权限，请参阅 [iot:ListRetainedMessages](#action_listretainedmessages)。

`iot:ListRetainedMessages`  
表示检索有关帐户保留邮件的摘要信息（而不是邮件内容）的权限。保留的消息是在设置了 RETAIN 标志的情况下发布并由存储的消息 AWS IoT Core。为此操作指定的资源 ARN 必须为 `*`。有关获取保留单条消息内容的权限，请参阅 [iot:GetRetainedMessage](#action_getretainpublish)。

`iot:Publish`  
代表向 MQTT 主题发布内容的权限。每次向代理发送 PUBLISH 请求时，均检查该权限。您可以使用此权限让客户端发布到特定主题模式。  
要授予 `iot:Publish` 权限，还必须授予 `iot:Connect` 权限。

`iot:Receive`  
表示接收来自的消息的权限 AWS IoT Core。每次向客户端交付消息时，都确认 `iot:Receive` 权限。由于每次交付时都会检查此权限，因此，可以使用它来吊销当前已订阅某个主题的客户端的权限。

`iot:RetainPublish`  
表示使用 RETAIN 标志集发布 MQTT 消息的权限。  
要授予 `iot:RetainPublish` 权限，还必须授予 `iot:Publish` 权限。

`iot:Subscribe`  
代表订阅主题筛选条件的权限。每次向代理发送 SUBSCRIBE 请求时，均检查该权限。用此权限让客户端可以订阅与特定主题模式相符的主题。  
要授予 `iot:Subscribe` 权限，还必须授予 `iot:Connect` 权限。Device Shadow 策略操作

`iot:DeleteThingShadow`  
表示删除事物的 Device Shadow 的权限。每次提出请求删除事物的 Device Shadow 内容时，都会检查 `iot:DeleteThingShadow` 权限。

`iot:GetThingShadow`  
表示检索事物的 Device Shadow 的权限。每次请求检索 Device Shadow 的内容时，都会检查 `iot:GetThingShadow` 权限。

`iot:ListNamedShadowsForThing`  
表示列出名为 Shadows 的事物的权限。每次请求列示名为 Shadows 的事物时，都会检查 `iot:ListNamedShadowsForThing` 权限。

`iot:UpdateThingShadow`  
表示更新设备的影子的权限。每次请求更新事物的 Device Shadow 的内容时，都会检查 `iot:UpdateThingShadow` 权限。

**注意**  
任务执行策略操作仅适用于 HTTP TLS 端点。如果您使用了 MQTT 端点，则必须使用本主题中定义的 MQTT 策略操作。  
有关演示此操作的任务执行策略的示例，请参阅使用 MQTT 协议的 [基本任务策略示例](basic-jobs-example.md)。Job 执行 AWS IoT Core 策略操作

`iotjobsdata:DescribeJobExecution`  
表示为给定事物检索任务执行的权限。每次请求获取任务执行时，都会检查 `iotjobsdata:DescribeJobExecution` 权限。

`iotjobsdata:GetPendingJobExecutions`  
表示一个权限，用于为事物检索未处于最终状态的任务的列表。每次请求检索该列表时，都会检查 `iotjobsdata:GetPendingJobExecutions` 权限。

`iotjobsdata:UpdateJobExecution`  
表示更新任务执行的权限。每次请求更新任务执行的状态时，都会检查 `iotjobsdata:UpdateJobExecution` 权限。

`iotjobsdata:StartNextPendingJobExecution`  
表示一个权限，用于为事物获取和启动下一个待处理任务执行。（即，将状态为 QUEUED 的任务执行更新为状态 IN\$1PROGRESS。） 每次请求启动下一个待处理任务执行，都会检查 `iotjobsdata:StartNextPendingJobExecution` 权限。AWS IoT Core 凭证提供商政策操作

`iot:AssumeRoleWithCertificate`  
表示允许通过基于证书的身份验证调用 AWS IoT Core 凭证提供商来担任 IAM 角色。每次向 AWS IoT Core 凭证提供者提出担任角色的请求时，都会检查`iot:AssumeRoleWithCertificate`权限。

# AWS IoT Core 动作资源
<a name="iot-action-resources"></a>

要为 AWS IoT Core 策略操作指定资源，请使用该资源的 Amazon 资源名称 (ARN)。所有资源都 ARNs 遵循以下格式：

```
arn:partition:iot:region:AWS-account-ID:Resource-type/Resource-name
```

下表列出了要为每种类型的操作指定的资源：ARN 示例适用于账户 ID `123456789012`，在分区 `aws` 中，并且特定于区域 `us-east-1`。有关格式的更多信息 ARNs，请参阅 AWS Identity and Access Management 用户指南[中的 Amazon 资源名称 (ARNs)](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference-arns.html)。


| Action | 资源类型 | 资源名称 | ARN 示例 | 
| --- | --- | --- | --- | 
| iot:Connect | client |  客户端的客户端 ID  | arn:aws:iot:us-east-1:123456789012:client/myClientId | 
| iot:DeleteConnection | client |  客户端的客户端 ID  | arn:aws:iot:us-east-1:123456789012:client/myClientId | 
| iot:DeleteThingShadow | thing |  事物的名称和影子的名称（如适用）  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne arn:aws:iot:us-east-1:123456789012:thing/thingOne/shadowOne  | 
| iotjobsdata:DescribeJobExecution | thing |  事物名称  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne  | 
| iotjobsdata:GetPendingJobExecutions | thing |  事物名称  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne  | 
| iot:GetRetainedMessage | topic |  保留的消息主题  |  arn:aws:iot:us-east-1:123456789012:topic/myTopicName  | 
| iot:GetThingShadow | thing |  事物的名称和影子的名称（如适用）  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne arn:aws:iot:us-east-1:123456789012:thing/thingOne/shadowOne  | 
| iot:ListNamedShadowsForThing | 全部 | 全部 |  \$1 | 
| iot:ListRetainedMessages | 全部 | 全部 |  \$1 | 
| iot:Publish | topic |  主题字符串  | arn:aws:iot:us-east-1:123456789012:topic/myTopicName | 
| iot:Receive | topic |  主题字符串  | arn:aws:iot:us-east-1:123456789012:topic/myTopicName | 
| iot:RetainPublish | topic |  用 REATIN 标志集发布的主题  |  arn:aws:iot:us-east-1:123456789012:topic/myTopicName  | 
| iotjobsdata:StartNextPendingJobExecution | thing |  事物名称  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne  | 
| iot:Subscribe | topicfilter | 主题筛选条件字符串 | arn:aws:iot:us-east-1:123456789012:topicfilter/myTopicFilter | 
| iotjobsdata:UpdateJobExecution | thing |  事物名称  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne  | 
| iot:UpdateThingShadow | thing |  事物的名称和影子的名称（如适用）  |  arn:aws:iot:us-east-1:123456789012:thing/thingOne arn:aws:iot:us-east-1:123456789012:thing/thingOne/shadowOne  | 
| iot:AssumeRoleWithCertificate | rolealias |  指向角色 ARN 的角色别名  |  arn:aws:iot:us-east-1:123456789012:rolealias/CredentialProviderRole\$1alias | 

# AWS IoT Core 策略变量
<a name="iot-policy-variables"></a>

AWS IoT Core 定义可在`Resource`或`Condition`块中的 AWS IoT Core 策略中使用的策略变量。评估策略时，将使用实际值替换策略变量。例如，如果设备连接到客户端 ID 为 100-234-3456 的 AWS IoT Core 消息代理，则策略文档中的`iot:ClientId`策略变量将被替换为 100-234-3456。

AWS IoT Core 策略可以使用通配符并遵循与 IAM 策略类似的惯例。在字符串中插入 `*`（星号）可以被视为通配符，匹配任何字符。例如，可以使用 `*` 在策略的 `Resource` 属性中描述多个 MQTT 主题名称。字符 `+` 和 `#` 在策略中被视为文字字符串。有关显示如何使用通配符的示例策略，请参阅[在 MQTT 和策略中使用通配符 AWS IoT Core](pub-sub-policy.md#pub-sub-policy-cert)。

还可以使用具有固定值的预定义策略变量来表示字符（这些字符本身有特殊的意义）。这些特殊字符包括 `$(*)`、`$(?)` 和 `$($)`。有关策略变量和特殊字符的更多信息，请参阅 [IAM 策略元素：变量和标签](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html)和[创建具有多个键或值的条件](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_multi-value-conditions.html)。

**Topics**
+ [基本 AWS IoT Core 策略变量](basic-policy-variables.md)
+ [事物策略变量](thing-policy-variables.md)
+ [X.509 证书策略变量 AWS IoT Core](cert-policy-variables.md)

# 基本 AWS IoT Core 策略变量
<a name="basic-policy-variables"></a>

AWS IoT Core 定义了以下基本策略变量：
+ `aws:SourceIp`：连接到 AWS IoT Core 消息代理的客户端的 IP 地址。
+ `iot:ClientId`：用于连接到 AWS IoT Core 消息代理的客户端 ID。
+ `iot:DomainName`：连接到的客户端的域名 AWS IoT Core。

**Topics**
+ [`ClientId` 和 `SourceIp` 策略变量示例](#basic-policy-variables-example)
+ [`iot:DomainName` 策略变量示例](#basic-policy-variables-example-domain)

## `ClientId` 和 `SourceIp` 策略变量示例
<a name="basic-policy-variables-example"></a>

以下 AWS IoT Core 策略显示了使用策略变量的策略。 `aws:SourceIp`可以在策略的条件元素中使用，以允许委托人仅在特定地址范围内发出 API 请求。有关示例，请参阅 [授权用户和云服务使用 AWS IoT 作业](iam-policy-users-jobs.md)。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/clientid1"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:ClientId}"
			],
			"Condition": {
				"IpAddress": {
					"aws:SourceIp": "123.45.167.89"
				}
			}
		}
	]
}
```

在这些示例中`${iot:ClientId}`，将替换为评估策略时连接到 AWS IoT Core 消息代理的客户端 ID。使用 `${iot:ClientId}` 等策略变量时，您可能会无意中开放对意外主题的访问权限。例如，如果您使用借助 `${iot:ClientId}` 来指定主题筛选条件的策略：

```
{
	"Effect": "Allow",
	"Action": [
		"iot:Subscribe"
	],
	"Resource": [
		"arn:aws:iot:us-east-1:123456789012:topicfilter/my/${iot:ClientId}/topic"
	]
}
```

客户端可使用 `+` 作为客户端 ID 来进行连接。这样，用户便可以订阅与主题筛选条件 `my/+/topic` 匹配的任何主题。要防范此类安全漏洞，请使用`iot:Connect`策略操作来控制 IDs 可以连接的客户端。例如，此策略仅允许那些客户端 ID 为 `clientid1` 的客户端建立连接：

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/clientid"
			]
		}
	]
}
```

**注意**  
不建议将策略变量 `${iot:ClientId}` 与 `Connect` 一起使用。不检查 `ClientId` 的值，因此，具有不同客户端 ID 的附加程序可以通过验证，但会导致连接断开。由于允许任何 `ClientId`，因此设置随机客户端 ID 可以绕过事物组策略。

## `iot:DomainName` 策略变量示例
<a name="basic-policy-variables-example-domain"></a>

您可以添加 `iot:DomainName` 策略变量来限制允许使用哪些域。添加 `iot:DomainName` 策略变量可以让设备仅连接到已配置的特定端点。

以下策略让设备可以连接到指定域。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": {
		"Sid": "AllowConnectionsToSpecifiedDomain",
		"Effect": "Allow",
		"Action": [
			"iot:Connect"
		],
		"Resource": "arn:aws:iot:us-east-1:123456789012:client/clientid",
		"Condition": {
			"StringEquals": {
				"iot:DomainName": "d1234567890abcdefghij-ats.iot.us-east-1.amazonaws.com"
			}
		}
	}
}
```

以下策略拒绝设备连接到指定域。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": {
		"Sid": "DenyConnectionsToSpecifiedDomain",
		"Effect": "Deny",
		"Action": [
			"iot:Connect"
		],
		"Resource": "arn:aws:iot:us-east-1:123456789012:client/clientid",
		"Condition": {
			"StringEquals": {
				"iot:DomainName": "d1234567890abcdefghij-ats.iot.us-east-1.amazonaws.com"
			}
		}
	}
}
```

有关策略条件运算符的信息，请参阅 [IAM JSON 策略元素：条件运算符](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_elements_condition_operators.html)。有关域配置的更多信息，请参阅[什么是域配置？](https://docs.aws.amazon.com//iot/latest/developerguide/iot-custom-endpoints-configurable.html)。

# 事物策略变量
<a name="thing-policy-variables"></a>

事物策略变量允许您编写基于事物名称、事物类型和事物属性值等事物属性授予或拒绝权限的 AWS IoT Core 策略。您可以使用事物策略变量来应用相同的策略来控制许多 AWS IoT Core 设备。有关设备预调配的更多信息，请参阅[设备预调配](iot-provision.html)。

如果您使用非独占事物关联，则同一证书可以附加到多个事物。为保持清晰的关联并避免潜在冲突，您必须将客户端 ID 与事物名称匹配。在这种情况下，您可以从事物连接到时发送的 MQTT `Connect` 消息中的客户端 ID 中获取事物名称。 AWS IoT Core

在 AWS IoT Core 策略中使用事物策略变量时，请记住以下事项。
+ 使用 [AttachThingPrincipal](https://docs.aws.amazon.com/iot/latest/apireference/API_AttachThingPrincipal.html)API 将证书或委托人（经过身份验证的 Amazon Cognito 身份）附加到事物。
+ 如果存在非独占事物关联，当您用事物策略变量替换事物名称时，MQTT 连接消息或 TLS 连接中的 `clientId` 值必须与事物名称完全匹配。

可用的事物策略变量如下：
+ `iot:Connection.Thing.ThingName`

  这将解析为正在评估策略的 AWS IoT Core 注册表中事物的名称。 AWS IoT Core 使用设备在进行身份验证时出示的证书来确定使用哪个东西来验证连接。只有当设备通过协议通过 MQTT 或 MQTT 进行连接时，此策略变量才可用。 WebSocket 
+ `iot:Connection.Thing.ThingTypeName`

  它解析为与要评估策略的事物关联的事物类型。MQTT/ WebSocket 连接的客户端 ID 必须与事物名称相同。仅当通过协议通过 MQTT 或 MQTT 进行连接时，此策略变量才可用。 WebSocket
+ `iot:Connection.Thing.Attributes[attributeName]`

  它解析为与要评估策略的事物关联的指定属性的值。事物最多可以具有 50 个属性。每个属性都可用作策略变量：`iot:Connection.Thing.Attributes[attributeName]`其中*attributeName*是属性的名称。 MQTT/WebSocket 连接的客户端 ID 必须与事物名称相同。此策略变量仅在通过 MQTT 或 MQTT 通过协议进行连接时可用。 WebSocket 
+ `iot:Connection.Thing.IsAttached`

  `iot:Connection.Thing.IsAttached: ["true"]`强制规定只有同时在委托人中注册 AWS IoT 并关联到委托人的设备才能访问策略内的权限。 AWS IoT Core 如果设备提供的证书未附加到注册表中的物联网事物，则可以使用此变量来阻止其连接 AWS IoT Core 。此变量具有值`true`，`false`表示连接对象已使用 API 附加到注册表中的证书或 Amazon Cognito 身份。[AttachThingPrincipal](https://docs.aws.amazon.com/iot/latest/apireference/API_AttachThingPrincipal.html)事物名称被视为客户端 ID。

如果您的客户端 ID 与事物名称匹配，或者如果您将证书独占附加到事物，则在策略定义中使用策略变量可以简化策略管理。您可以使用事物策略变量定义单个策略，而不是为每个物联网事物创建单独的策略。此策略可以动态应用于所有设备。以下是一个示例策略来说明其工作原理。有关更多信息，请参阅 [将 AWS IoT 事物关联到 MQTT 客户端连接](exclusive-thing.md)。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Condition": {
				"StringLike": {
					"iot:ClientId": "*${iot:Connection.Thing.Attributes[envType]}"
				}
			},
			"Effect": "Allow",
			"Action": "iot:Connect",
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/*"
		}
	]
}
```

 AWS IoT Core 如果事物的客户端 ID 以其`envType`属性的值结尾，则此策略示例允许它们进行连接。只有具有匹配客户端 ID 模式的事物才被允许连接。

# X.509 证书策略变量 AWS IoT Core
<a name="cert-policy-variables"></a>

X.509 证书策略变量有助于编写策略。 AWS IoT Core 这些策略根据 X.509 证书属性授予权限。以下部分介绍如何使用这些证书策略变量。

**重要**  
如果您的 X.509 证书不包含特定的证书属性，但在策略文档中使用了相应的证书策略变量，则策略评估可能会导致意外行为。

## CertificateId
<a name="cert-policy-variables-certid"></a>

在 [RegisterCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCertificate.html)API 中，`certificateId`显示在响应正文中。要获取有关您的证书的信息，请使用`certificateId`中的[DescribeCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeCertificate.html)。

## 颁发者属性
<a name="issuer-attributes"></a>

以下 AWS IoT Core 策略变量根据证书颁发者设置的证书属性支持允许或拒绝权限。
+ `iot:Certificate.Issuer.DistinguishedNameQualifier`
+ `iot:Certificate.Issuer.Country`
+ `iot:Certificate.Issuer.Organization`
+ `iot:Certificate.Issuer.OrganizationalUnit`
+ `iot:Certificate.Issuer.State`
+ `iot:Certificate.Issuer.CommonName`
+ `iot:Certificate.Issuer.SerialNumber`
+ `iot:Certificate.Issuer.Title`
+ `iot:Certificate.Issuer.Surname`
+ `iot:Certificate.Issuer.GivenName`
+ `iot:Certificate.Issuer.Initials`
+ `iot:Certificate.Issuer.Pseudonym`
+ `iot:Certificate.Issuer.GenerationQualifier` 

## 使用者属性
<a name="subject-attributes"></a>

以下 AWS IoT Core 策略变量支持根据证书颁发者设置的证书主题属性授予或拒绝权限。
+ `iot:Certificate.Subject.DistinguishedNameQualifier`
+ `iot:Certificate.Subject.Country`
+ `iot:Certificate.Subject.Organization`
+ `iot:Certificate.Subject.OrganizationalUnit`
+ `iot:Certificate.Subject.State`
+ `iot:Certificate.Subject.CommonName`
+ `iot:Certificate.Subject.SerialNumber`
+ `iot:Certificate.Subject.Title`
+ `iot:Certificate.Subject.Surname`
+ `iot:Certificate.Subject.GivenName`
+ `iot:Certificate.Subject.Initials`
+ `iot:Certificate.Subject.Pseudonym`
+ `iot:Certificate.Subject.GenerationQualifier` 

X.509 证书为这些属性提供了包含一个或多个值的选项。默认情况下，每个多值属性的策略变量会返回第一个值。例如，`Certificate.Subject.Country` 属性可能包含国家/地区名称列表，但在策略中进行评估时，`iot:Certificate.Subject.Country` 会替换为第一个国家/地区名称。

您可以使用从 1 开始的索引请求第一个值以外的特定属性值。例如，`iot:Certificate.Subject.Country.1` 由 `Certificate.Subject.Country` 属性中第二个国家/地区名称替换。如果您指定不存在的索引值（例如，如果您在只有两个值分配到属性时请求第三个值），则不会执行替换功能，并且授权将失败。您可以在策略变量名称中使用 `.List` 后缀指定属性的所有值。

## 颁发者备用名称属性
<a name="issuer-alternate-name-attributes"></a>

以下 AWS IoT Core 策略变量支持根据证书颁发者设置的颁发者备用名称属性授予或拒绝权限。
+ `iot:Certificate.Issuer.AlternativeName.RFC822Name`
+ `iot:Certificate.Issuer.AlternativeName.DNSName`
+ `iot:Certificate.Issuer.AlternativeName.DirectoryName`
+ `iot:Certificate.Issuer.AlternativeName.UniformResourceIdentifier`
+ `iot:Certificate.Issuer.AlternativeName.IPAddress`

## 使用者备用名称属性
<a name="subject-alternate-name-attributes"></a>

以下 AWS IoT Core 策略变量支持根据证书颁发者设置的主题备用名称属性授予或拒绝权限。
+ `iot:Certificate.Subject.AlternativeName.RFC822Name`
+ `iot:Certificate.Subject.AlternativeName.DNSName`
+ `iot:Certificate.Subject.AlternativeName.DirectoryName`
+ `iot:Certificate.Subject.AlternativeName.UniformResourceIdentifier`
+ `iot:Certificate.Subject.AlternativeName.IPAddress`

## 其它属性
<a name="other-attributes"></a>

根据证书`iot:Certificate.SerialNumber`的序列号，您可以使用来允许或拒绝对 AWS IoT Core 资源的访问。`iot:Certificate.AvailableKeys` 策略变量包含具有值的所有证书策略变量的名称。

# 使用 X.509 证书策略变量
<a name="use-policy-variables"></a>

本主题提供有关如何使用证书策略变量的详细信息。X.509 证书策略变量对于您根据 X.509 证书属性创建授予权限的 AWS IoT Core 策略至关重要。如果您的 X.509 证书不包含特定的证书属性，但在策略文档中使用了相应的证书策略变量，则策略评估可能会导致意外行为。这是因为缺少的策略变量不会在策略声明中进行评估。

**Topics**
+ [X.509 证书示例](#certificate-example)
+ [使用证书颁发者属性作为证书策略变量](#issuer-attributes-policy)
+ [使用证书主题属性作为证书策略变量](#subject-attributes-policy)
+ [使用证书颁发者备用名称属性作为证书策略变量](#issuer-alternate-name-attributes-policy)
+ [使用证书主题备用名称属性作为证书策略变量](#subject-alternate-name-attributes-policy)
+ [使用其他证书属性作为证书策略变量](#other-attributes-policy)
+ [X.509 证书策略变量限制](#policy-limits)
+ [使用证书策略变量的策略示例](#example-attributes-policy)

## X.509 证书示例
<a name="certificate-example"></a>

典型的 X.509 证书可能如下所示。此示例证书包括证书属性。在评估 AWS IoT Core 策略期间，以下证书属性将填充为证书策略变量：`Serial Number`、`Issuer`、`Subject`、`X509v3 Issuer Alternative Name`、和 `X509v3 Subject Alternative Name`。

```
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            92:12:85:cb:b7:a5:e0:86
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, O=IoT Devices, OU=SmartHome, ST=WA, CN=IoT Devices Primary CA, 
				GN=Primary CA1/initials=XY/dnQualifier=Example corp,
				SN=SmartHome/ title=CA1/pseudonym=Primary_CA/generationQualifier=2/serialNumber=987		
        Validity
            Not Before: Mar 26 03:25:40 2024 GMT
            Not After : Apr 28 03:25:40 2025 GMT
        Subject: C=US, O=IoT Devices, OU=LightBulb, ST=NY, CN=LightBulb Device Cert, 
				GN=Bulb/initials=ZZ/dnQualifier=Bulb001, 
				SN=Multi Color/title=RGB/pseudonym=RGB Device/generationQualifier=4/serialNumber=123
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                RSA Public-Key: (2048 bit)
                Modulus:
                    << REDACTED >>
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            X509v3 Key Usage: 
                Digital Signature, Non Repudiation, Key Encipherment
            X509v3 Subject Alternative Name: 
                DNS:example.com, IP Address:1.2.3.4, URI:ResourceIdentifier001, email:device1@example.com, DirName:/C=US/O=IoT/OU=SmartHome/CN=LightBulbCert
            X509v3 Issuer Alternative Name: 
                DNS:issuer.com, IP Address:5.6.7.8, URI:PrimarySignerCA, email:primary@issuer.com, DirName:/C=US/O=Issuer/OU=IoT Devices/CN=Primary Issuer CA
    Signature Algorithm: sha256WithRSAEncryption
         << REDACTED >>
```

## 使用证书颁发者属性作为证书策略变量
<a name="issuer-attributes-policy"></a>

下表详细说明了如何在 AWS IoT Core 策略中填充证书颁发者属性。


**要在策略中填充的颁发者属性**  

| 证书颁发者属性 | 证书策略变量 | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/use-policy-variables.html)  | 

## 使用证书主题属性作为证书策略变量
<a name="subject-attributes-policy"></a>

下表详细说明了如何在 AWS IoT Core 策略中填充证书主题属性。


**要在策略中填充的主题属性**  

| 证书主题属性 | 证书策略变量 | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/use-policy-variables.html)  | 

## 使用证书颁发者备用名称属性作为证书策略变量
<a name="issuer-alternate-name-attributes-policy"></a>

下表详细说明了如何在 AWS IoT Core 策略中填充证书颁发者备用名称属性。


**要在策略中填充的颁发者备用名称属性**  

| X509v3 颁发者备用名称 | 策略中的属性 | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/use-policy-variables.html)  | 

## 使用证书主题备用名称属性作为证书策略变量
<a name="subject-alternate-name-attributes-policy"></a>

下表详细说明了如何在 AWS IoT Core 策略中填充证书主题备用名称属性。


**要在策略中填充的主题备用名称属性**  

| X509v3 主题备用名称 | 策略中的属性 | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/use-policy-variables.html)  | 

## 使用其他证书属性作为证书策略变量
<a name="other-attributes-policy"></a>

下表详细介绍了如何在 AWS IoT Core 策略中填充其他证书属性。


**要在策略中填充的其他属性**  

| 其他证书属性 | 证书策略变量 | 
| --- | --- | 
|  `Serial Number: 92:12:85:cb:b7:a5:e0:86`  |  `iot:Certificate.SerialNumber = 10525622389124227206`  | 

## X.509 证书策略变量限制
<a name="policy-limits"></a>

以下限制适用于 X.509 证书策略变量：

缺少的策略变量  
如果您的 X.509 证书不包含特定的证书属性，但在策略文档中使用了相应的证书策略变量，则策略评估可能会导致意外行为。这是因为缺少的策略变量不会在策略声明中进行评估。

证书 SerialNumber 格式  
AWS IoT Core 将证书序列号视为十进制整数的字符串表示形式。例如，如果策略只允许使用与证书序列号匹配的客户端 ID 进行连接，则客户端 ID 必须是十进制格式的序列号。

通配符  
如果证书属性中有通配符，则策略变量不会由证书属性值替换。这将会在策略文档中保留 `${policy-variable}` 文本。这可能会导致授权失败。可以使用以下通配符：`*`、`$`、`+`、`?` 和 `#`。

数组字段  
包含数组的证书属性限制为五项。其它的项将被忽略。

字符串长度  
所有字符串值的长度限制为 1024 个字符。如果证书属性包含超过 1024 个字符的字符串，则策略变量不会由证书属性值替换。这将会在策略文档中保留 `${policy-variable}`。这可能会导致授权失败。

特殊字符  
在策略变量中使用时，任何特殊字符（例如 `,`、`"`、`\`、`+`、`=`、`<`、`>` 和 `;`）都必须使用反斜杠 (`\`) 作为前缀。例如，`Amazon Web Services O=Amazon.com Inc. L=Seattle ST=Washington C=US` 改为 `Amazon Web Service O\=Amazon.com Inc. L\=Seattle ST\=Washington C\=US`。

## 使用证书策略变量的策略示例
<a name="example-attributes-policy"></a>

以下策略文档允许使用与证书序列号匹配的客户端 ID 进行连接，并允许发布到与下列模式匹配的主题：`${iot:Certificate.Subject.Organization}/device-stats/${iot:ClientId}/*`。

**重要**  
如果您的 X.509 证书不包含特定的证书属性，但在策略文档中使用了相应的证书策略变量，则策略评估可能会导致意外行为。这是因为缺少的策略变量不会在策略声明中进行评估。例如，如果您将以下策略文档附加到不包含 `iot:Certificate.Subject.Organization` 属性的证书，则在策略评估期间将不会填充 `iot:Certificate.Subject.Organization` 证书策略变量。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Certificate.SerialNumber}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/${iot:Certificate.Subject.Organization}/device-stats/${iot:ClientId}/*"
			]
		}
	]
}
```

您也可以使用 [Null 条件运算符](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Null)来确保在策略评估期间填充策略中所用的证书策略变量。以下策略文档仅在存在证书序列号和证书主题公用名属性时才允许在证书中使用 `iot:Connect`。

所有证书策略变量都具有字符串值，因此支持所有[字符串条件运算符](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String)。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/*"
			],
			"Condition": {
				"Null": {
					"iot:Certificate.SerialNumber": "false",
					"iot:Certificate.Subject.CommonName": "false"
				}
			}
		}
	]
}
```

# 防止跨服务混淆座席
<a name="cross-service-confused-deputy-prevention"></a>

*混淆代理问题*是一个安全问题，即没有执行操作权限的实体可能会迫使更具权限的实体执行该操作。在中 AWS，跨服务模仿可能会导致混乱的副手问题。一个服务（*呼叫服务*) 调用另一项服务（*所谓的服务*)时，可能会发生跨服务模拟。可以操纵调用服务以使用其权限对另一个客户的资源进行操作，否则该服务不应有访问权限。为了防止这种情况， AWS 提供可帮助您保护所有服务的服务委托人数据的工具，这些服务委托人有权限访问账户中的资源。

要限制为资源 AWS IoT 提供其他服务的权限，我们建议在资源策略中使用[https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn)和[https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount)全局条件上下文密钥。如果使用两个全局条件上下文键，在同一策略语句中使用时，`aws:SourceAccount` 值和 `aws:SourceArn` 值中的账户必须使用相同的账户 ID。

防止混淆代理问题最有效的方法是使用具有资源完整 Amazon 资源名称（ARN）的 `aws:SourceArn` 全局条件上下文键。对于 AWS IoT，您`aws:SourceArn`必须遵守以下格式：`arn:aws:iot:region:account-id:resource-type/resource-id`资源特定权限或`arn:aws:iot:region:account-id:*`。resource-id 可以是允许资源的名称或 ID，也可以是允许资源的通配符语句。 IDs确保*region*与您的 AWS IoT 地区相匹配，并且与您的客户账户 ID *account-id* 相匹配。

以下示例说明如何通过在 AWS IoT 角色信任策略中使用`aws:SourceArn`和`aws:SourceAccount`全局条件上下文密钥来防止出现混淆的代理问题。有关更多示例，请参阅[混淆代理问题防范详细示例](#cross-service-confused-deputy-prevention-examples)。

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Service":"iot.amazonaws.com"
         },
         "Action":"sts:AssumeRole",
         "Condition":{
            "StringEquals":{
               "aws:SourceAccount":"123456789012"
        },
            "ArnLike":{
               "aws:SourceArn":"arn:aws:iot:us-east-1:123456789012:*"
        }
         }
      }
   ]
}
```

**注意**  
如果您遇到拒绝访问错误，可能是因为与 AWS 安全令牌服务（STS）的服务集成不支持 `aws:SourceArn` 和 `aws:SourceAccount` 上下文键。

## 混淆代理问题防范详细示例
<a name="cross-service-confused-deputy-prevention-examples"></a>

**本节提供了详细的示例，说明如何通过在 AWS IoT 角色信任策略中使用`aws:SourceArn`和`aws:SourceAccount`全局条件上下文密钥来防止混淆副手问题。**
+ [实例集预置](#cross-service-confused-deputy-prevention-fleet-provision)
+ [JITP](#cross-service-confused-deputy-prevention-JITP)
+ [凭证提供者](#cross-service-confused-deputy-prevention-credential-provider)

### 实例集预置
<a name="cross-service-confused-deputy-prevention-fleet-provision"></a>

您可以使用预调配模板资源配置[实例集预调配](https://docs.aws.amazon.com/iot/latest/developerguide/iot-provision.html)。当预调配模板引用预调配角色时，该角色的信任策略可以包括 `aws:SourceArn` 和 `aws:SourceAccount` 条件键。这些键限制了配置可以调用 `sts:AssumeRole` 请求的资源。

使用以下信任策略的角色只能由 `SourceArn` 中指定的预调配模板的物联网主体 (`iot.amazonaws.com`) 担任。

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Service":"iot.amazonaws.com"
         },
         "Action":"sts:AssumeRole",
         "Condition":{
            "StringEquals":{
               "aws:SourceAccount":"123456789012"
        },
            "ArnLike":{
               "aws:SourceArn":"arn:aws:iot:us-east-1:123456789012:provisioningtemplate/example_template"
        }
         }
      }
   ]
}
```

### JITP
<a name="cross-service-confused-deputy-prevention-JITP"></a>

在[just-in-time 配置 (JITP)](https://docs.aws.amazon.com//iot/latest/developerguide/jit-provisioning.html) 中，您可以将配置模板用作独立于 CA 的资源，也可以将模板主体和角色定义为 CA 证书配置的一部分。 AWS IoT 角色信任策略`aws:SourceArn`中的值取决于您如何定义配置模板。

#### 将预调配模板定义为单独的资源
<a name="cross-service-confused-deputy-prevention-JITP-template"></a>

如果您将预调配模板定义为单独的资源，则 `aws:SourceArn` 的值可以是 `"arn:aws:iot:region:account-id:provisioningtemplate/example_template"`。您可以使用 [实例集预置](#cross-service-confused-deputy-prevention-fleet-provision) 中的示例策略。

#### 在 CA 证书中定义预调配模板
<a name="cross-service-confused-deputy-prevention-JITP-CA"></a>

如果您在 CA 证书资源中定义预调配模板，则 `aws:SourceArn` 的值可以为 `"arn:aws:iot:region:account-id:cacert/cert_id"` 或 `"arn:aws:iot:region:account-id:cacert/*"`。如果资源标识符（例如 CA 证书的 ID）在创建时未知，您可以使用通配符。

使用以下信任策略的角色只能由 `SourceArn` 中指定的 CA 证书的物联网主体 (`iot.amazonaws.com`) 担任。

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Service":"iot.amazonaws.com"
         },
         "Action":"sts:AssumeRole",
         "Condition":{
            "StringEquals":{
               "aws:SourceAccount":"123456789012"
        },
            "ArnLike":{
               "aws:SourceArn":"arn:aws:iot:us-east-1:123456789012:cacert/8ecde6884f3d87b1125ba31ac3fcb13d7016de7f57cc904fe1cb97c6ae98196e"
        }
         }
      }
   ]
}
```

创建 CA 证书时，可以在注册配置中引用预调配角色。预调配角色的信任策略可使用 `aws:SourceArn` 来限制该角色可以担任的资源。[但是，在最初的 Register CACertificate 调用以注册 CA 证书期间，您无法在条件中指定 CA 证书的 ARN。](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCACertificate.html) `aws:SourceArn`

要解决此问题，即为注册的特定 CA 证书指定配置角色信任策略 AWS IoT Core，您可以执行以下操作：
+ 首先，在CACertificate不提供`RegistrationConfig`参数的情况下调用 [Re](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCACertificate.html) gister。
+ 注册 CA 证书后 AWS IoT Core，对其调用 [Up CACertificate date](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateCACertificate.html)。

  在更新CACertificate 调用中，提供`RegistrationConfig`包含配置角色信任策略的，`aws:SourceArn`设置为新注册的 CA 证书的 ARN。

### 凭证提供者
<a name="cross-service-confused-deputy-prevention-credential-provider"></a>

对于[AWS IoT Core 凭证提供者](https://docs.aws.amazon.com//iot/latest/developerguide/authorizing-direct-aws.html)，请使用 AWS 账户 您在中创建角色别名的相同语句`aws:SourceAccount`，并指定与中角色别名资源类型的资源 ARN 相匹配的语句。`aws:SourceArn`创建供 AWS IoT Core 凭证提供商使用的 IAM 角色时，您必须在`aws:SourceArn`条件中包含可能需要担任该角色的任何角色别名，从而授权跨服务请求。 ARNs `sts:AssumeRole`

使用以下信任策略的角色只能由 `SourceArn` 中指定角色别名的 AWS IoT Core 凭证提供者主体 (`credentials.iot.amazonaws.com`) 担任。如果主体尝试检索 `aws:SourceArn` 条件中未指定的角色别名的凭证，则即使其他角色别名引用相同的 IAM 角色，该请求也会被拒绝。

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "credentials.iot.amazonaws.com"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "aws:SourceAccount": "123456789012"
        },
        "ArnLike": {
          "aws:SourceArn": "arn:aws:iot:us-east-1:123456789012:rolealias/example_rolealias"
        }
      }
    }
  ]
}
```

# AWS IoT Core 策略示例
<a name="example-iot-policies"></a>

本节中的策略示例说明了用于完成 AWS IoT Core中常见任务的策略文档。为解决方案创建策略时，您可以将其作为启动示例。<a name="example-iot-policies-elements"></a>

本节中的示例使用以下策略元素：
+ [AWS IoT Core 政策行动](iot-policy-actions.md)
+ [AWS IoT Core 动作资源](iot-action-resources.md)
+ [AWS IoT 基于身份的策略示例](security_iam_id-based-policy-examples.md)
+ [基本 AWS IoT Core 策略变量](basic-policy-variables.md)
+ [X.509 证书策略变量 AWS IoT Core](cert-policy-variables.md)

**Topics**
+ [连接策略示例](connect-policy.md)
+ [发布/订阅策略示例](pub-sub-policy.md)
+ [连接和发布策略示例](connect-and-pub.md)
+ [保留的消息策略示例](retained-message-policy-examples.md)
+ [证书策略示例](certificate-policy-examples.md)
+ [事物策略示例](thing-policy-examples.md)
+ [基本任务策略示例](basic-jobs-example.md)

# 连接策略示例
<a name="connect-policy"></a>

以下策略拒绝对客户端 IDs `client1`和连接`client2`的权限 AWS IoT Core，同时允许设备使用客户端 ID 进行连接。客户端 ID 与在注册表中 AWS IoT Core 注册并附加到用于连接的主体上的事物的名称相匹配：

**注意**  
对于注册的设备，我们建议您将[事物策略变量](thing-policy-variables.md)用于 `Connect` 操作，并将事物附加到用于连接的主体。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Deny",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/client1",
				"arn:aws:iot:us-east-1:123456789012:client/client2"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			],
			"Condition": {
				"Bool": {
					"iot:Connection.Thing.IsAttached": "true"
				}
			}
		}
	]
}
```

以下策略授予 AWS IoT Core 使用客户端 ID 进行连接的权限`client1`。此策略示例适用于未注册的设备。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/client1"
			]
		}
	]
}
```

## MQTT 持久会话策略示例
<a name="persistent-sessions-examples"></a>

`connectAttributes` 允许您在 IAM policy 中指定要在连接消息中使用的属性，如 `PersistentConnect` 和 `LastWill`。有关更多信息，请参阅 [使用 ConnectAttributes](mqtt.md#connect-attribute)。

以下策略允许连接 `PersistentConnect` 特征：

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect"
					]
				}
			}
		}
	]
}
```

以下策略不允许 `PersistentConnect`，但允许使用其它特征：

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringNotEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect"
					]
				}
			}
		}
	]
}
```

上述策略也可以使用 `StringEquals` 表达，但允许使用包括新特征在内的任何其它特征：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1"
        },
        {
            "Effect": "Deny",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:ConnectAttributes": [
                        "PersistentConnect"
                    ]
            }
        }
        }
    ]
}
```

以下策略允许通过 `PersistentConnect` 和 `LastWill` 连接，但不允许使用任何其它新特征：

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect",
						"LastWill"
					]
				}
			}
		}
	]
}
```

以下策略允许客户端进行干净连接，无论是否具有 `LastWill`，但不允许使用其它特征：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
        "Effect": "Allow",
        "Action": [
            "iot:Connect"
        ],
        "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
        "Condition": {
            "StringEquals": {
                "iot:ConnectAttributes": "LastWill"
        }
        }
    }]
}
```

以下策略仅允许使用默认特征进行连接：

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": []
				}
			}
		}
	]
}
```

以下策略仅允许使用 `PersistentConnect` 连接，但只要连接使用 `PersistentConnect`，则允许使用任何新特征：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:ConnectAttributes": [
                        "PersistentConnect"
                    ]
            }
        }
        }
    ]
}
```

以下策略规定连接必须同时使用 `PersistentConnect` 和 `LastWill`，而不允许使用新特征：

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect",
						"LastWill"
					]
				}
			}
		},
		{
			"Effect": "Deny",
			"Action": [
				"iot:Connect"
			],
			"Resource": "*",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"PersistentConnect"
					]
				}
			}
		},
		{
			"Effect": "Deny",
			"Action": [
				"iot:Connect"
			],
			"Resource": "*",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"LastWill"
					]
				}
			}
		},
		{
			"Effect": "Deny",
			"Action": [
				"iot:Connect"
			],
			"Resource": "*",
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": []
				}
			}
		}
	]
}
```

以下策略不能拥有 `PersistentConnect`，但可以有 `LastWill`，不允许使用任何其它新特征：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:ConnectAttributes": [
                        "PersistentConnect"
                    ]
            }
        }
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
            "Condition": {
                "ForAllValues:StringEquals": {
                    "iot:ConnectAttributes": [
                        "LastWill"
                    ]
            }
        }
        }
    ]
}
```

以下策略仅允许包括带有主题 `"my/lastwill/topicName"` 的 `LastWill` 客户端连接，同时允许任何使用 `LastWill` 主题的特征:

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
            "Condition": {
                "ArnEquals": {
                "iot:LastWillTopic": "arn:aws:iot:us-east-1:123456789012:topic/my/lastwill/topicName"
            }
        }
        }
    ]
}
```

以下策略仅允许使用特定 `LastWillTopic` 的干净连接，同时允许任何使用 `LastWillTopic` 的特征：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "arn:aws:iot:us-east-1:123456789012:client/client1",
            "Condition": {
                "ArnEquals": {
                "iot:LastWillTopic": "arn:aws:iot:us-east-1:123456789012:topic/my/lastwill/topicName"
            }
        }
        },
        {
            "Effect": "Deny",
            "Action": [
                "iot:Connect"
            ],
            "Resource": "*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:ConnectAttributes": [
                        "PersistentConnect"
                    ]
            }
        }
        }
    ]
}
```

# 发布/订阅策略示例
<a name="pub-sub-policy"></a>

您使用的策略取决于您的连接方式 AWS IoT Core。您可以使用 MQTT 客户端、HTTP 或 WebSocket。 AWS IoT Core 通过 MQTT 客户端连接时，将使用 X.509 证书进行身份验证。当你通过 HTTP 或 WebSocket 协议连接时，你就是在使用签名版本 4 和 Amazon Cognito 进行身份验证。

**注意**  
对于注册的设备，我们建议您将[事物策略变量](thing-policy-variables.md)用于 `Connect` 操作，并将事物附加到用于连接的主体。

**Topics**
+ [在 MQTT 和策略中使用通配符 AWS IoT Core](#pub-sub-policy-cert)
+ [发布、订阅和接收消息的政策（ to/from 特定主题）](#pub-sub-specific-topic)
+ [发布、订阅和接收带有特定前缀的消息 to/from 主题的政策](#pub-sub-policy-specific-topic-prefix)
+ [发布、订阅和接收特定于每台设备的消息 to/from 主题的政策](#pub-sub-specific-topic-device)
+ [发布、订阅和接收消息 to/from 主题的策略，主题名称中包含事物属性的主题](#pub-sub-topic-attribute)
+ [拒绝向主题名称的子主题发布消息的策略](#pub-sub-deny-publish)
+ [拒绝接收来自主题名称的子主题的消息的策略](#pub-sub-deny-receive)
+ [使用 MQTT 通配符订阅主题的策略](#pub-sub-topic-wildcard)
+ [适用于 HTTP 和 WebSocket 客户端的策略](#pub-sub-policy-cognito)

## 在 MQTT 和策略中使用通配符 AWS IoT Core
<a name="pub-sub-policy-cert"></a>

MQTT 和 AWS IoT Core 策略具有不同的通配符，您应在仔细考虑后选择它们。在 MQTT 中，在 M [QTT 主题过滤器中使用通配符`+`和`#`来订阅多个主题](https://docs.aws.amazon.com/iot/latest/developerguide/topics.html#topicfilters)名称。 AWS IoT Core 策略使用`*`和`?`作为通配符并遵守 [IAM 策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_grammar.html#policies-grammar-json)的惯例。在策略文档中，`*` 表示字符的任意组合，问号 `?` 表示任何单个字符。在策略文档中，MQTT 通配符 `+` 和 `#` 被视为没有特殊意义的字符。要在策略的 `resource` 属性中描述多个主题名称和主题筛选条件，请使用 `*` 和 `?` 通配符代替 MQTT 通配符。

如果选择要在策略文档中使用的通配符，请考虑 `*` 字符不限于单个主题级别。在 MQTT 主题筛选器中，`+` 角色仅限于单个主题级别。为了帮助将通配符规范限制为单个 MQTT 主题筛选条件级别，请考虑使用多个 `?` 字符。有关在策略资源中使用通配符的更多信息以及通配符匹配内容的更多示例，请参阅在资源[中使用通配符](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_elements_resource.html#reference_policies_elements_resource_wildcards)。 ARNs

下表显示了 MQTT 和 MQTT 客户端的 AWS IoT Core 策略中使用的不同通配符。


| 通配符 | 是 MQTT 通配符 | MQTT 中的示例 | 是 AWS IoT Core 策略通配符吗 | MQTT AWS IoT Core 客户端策略中的示例 | 
| --- | --- | --- | --- | --- | 
| \$1 | 是 | some/\$1 | 否 | 不适用 | 
| \$1 | 是 | some/\$1/topic | 否 | 不适用 | 
| \$1 | 否 | 不适用 | 是 | `topicfilter/some/*/topic` `topicfilter/some/sensor*/topic`  | 
| ? | 否 | 不适用 | 是 |  `topic/some/?????/topic` `topicfilter/some/sensor???/topic`  | 

## 发布、订阅和接收消息的政策（ to/from 特定主题）
<a name="pub-sub-specific-topic"></a>

以下是注册和未注册设备发布、订阅和接收名为 “some\$1specific\$1topic” 主题 to/from 的消息的示例。这些示例还强调了 `Publish` 和 `Receive` 使用“主题”作为资源，`Subscribe` 使用“主题筛选器”作为资源。

------
#### [ Registered devices ]

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用与注册表中事物名称匹配的 ClientID 进行连接。它还为名为“some\$1specific\$1topic”的主题提供 `Publish`、`Subscribe` 和 `Receive` 权限。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			],
			"Condition": {
				"Bool": {
					"iot:Connection.Thing.IsAttached": "true"
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/some_specific_topic"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Subscribe"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topicfilter/some_specific_topic"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Receive"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/some_specific_topic"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

对于未在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用 clientID1、clientID2 或 clientID3 进行连接。它还为名为“some\$1specific\$1topic”的主题提供 `Publish`、`Subscribe` 和 `Receive` 权限。

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/some_specific_topic"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topicfilter/some_specific_topic"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/some_specific_topic"
            ]
        }
    ]
}
```

------

## 发布、订阅和接收带有特定前缀的消息 to/from 主题的政策
<a name="pub-sub-policy-specific-topic-prefix"></a>

以下是注册和未注册设备发布、订阅和接收以 “topic\$1prefix” 为前缀的消息 to/from 主题的示例。

**注意**  
请注意此示例中通配符 `*` 的使用。尽管 `*` 对于在单个语句中为多个主题名称提供权限很有用，但它给设备提供的权限可能比所需权限更多，从而导致意想不到的后果。因此，我们建议您要经过深思熟虑后再使用通配符 `*`。

------
#### [ Registered devices ]

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用与注册表中事物名称匹配的 ClientID 进行连接。它还会为具有前缀“topic\$1prefix”的主题提供 `Publish`、`Subscribe` 和 `Receive` 权限。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			],
			"Condition": {
				"Bool": {
					"iot:Connection.Thing.IsAttached": "true"
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish",
				"iot:Receive"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/topic_prefix*"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Subscribe"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topicfilter/topic_prefix*"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

对于未在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用 clientID1、clientID2 或 clientID3 进行连接。它还会为具有前缀“topic\$1prefix”的主题提供 `Publish`、`Subscribe` 和 `Receive` 权限。

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish",
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/topic_prefix*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topicfilter/topic_prefix*"
            ]
        }
    ]
}
```

------

## 发布、订阅和接收特定于每台设备的消息 to/from 主题的政策
<a name="pub-sub-specific-topic-device"></a>

以下是已注册和未注册设备发布、订阅和接收特定于给定设备的消息 to/from 主题的示例。

------
#### [ Registered devices ]

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用与注册表中事物名称匹配的 ClientID 进行连接。它提供向特定事物主题 (`sensor/device/${iot:Connection.Thing.ThingName}`) 发布内容的权限，还提供订阅特定事物主题 (`command/device/${iot:Connection.Thing.ThingName}`) 和从特定事物主题接收内容的权限。如果注册表中的事物名称为 “thing1”，则设备将能够发布到主题 “sensor/device/thing1". The device will also be able to subscribe to and receive from the topic "command/device/thing1”。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			],
			"Condition": {
				"Bool": {
					"iot:Connection.Thing.IsAttached": "true"
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/sensor/device/${iot:Connection.Thing.ThingName}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Subscribe"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topicfilter/command/device/${iot:Connection.Thing.ThingName}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Receive"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/command/device/${iot:Connection.Thing.ThingName}"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

对于未在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用 clientID1、clientID2 或 clientID3 进行连接。它提供发布到客户特定主题 (`sensor/device/${iot:ClientId}`) 的权限，还提供订阅客户特定主题 (`command/device/${iot:ClientId}`) 和从此客户特定主题接收内容的权限。如果设备以 clientId1 的身份与 clientId 连接，则它将能够发布到主题 “1”。sensor/device/clientId该设备还将能够订阅和接收 `device/clientId1/command` 主题的内容。

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/sensor/device/${iot:Connection.Thing.ThingName}"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topicfilter/command/device/${iot:Connection.Thing.ThingName}"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/command/device/${iot:Connection.Thing.ThingName}"
            ]
        }
    ]
}
```

------

## 发布、订阅和接收消息 to/from 主题的策略，主题名称中包含事物属性的主题
<a name="pub-sub-topic-attribute"></a>

下面显示了注册设备发布、订阅和接收名称包含事物属性的消息 to/from 主题的示例。

**注意**  
仅在 AWS IoT Core 注册表中注册的设备存在事物属性。对于未注册的设备，没有相应的示例。

------
#### [ Registered devices ]

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用与注册表中事物名称匹配的 ClientID 进行连接。它提供发布到主题 (`sensor/${iot:Connection.Thing.Attributes[version]}`)，以及订阅主题名称中包含事物属性的主题 (`command/${iot:Connection.Thing.Attributes[location]}`) 和从该主题接收内容的权限。如果注册表中的事物名称`version=v1`包含和`location=Seattle`，则设备将能够发布到主题 “sensor/v1", and subscribe to and receive from the topic "command/Seattle”。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			],
			"Condition": {
				"Bool": {
					"iot:Connection.Thing.IsAttached": "true"
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/sensor/${iot:Connection.Thing.Attributes[version]}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Subscribe"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topicfilter/command/${iot:Connection.Thing.Attributes[location]}"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Receive"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/command/${iot:Connection.Thing.Attributes[location]}"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

由于仅在 AWS IoT Core 注册表中注册的设备存在事物属性，因此未注册的事物没有相应的示例。

------

## 拒绝向主题名称的子主题发布消息的策略
<a name="pub-sub-deny-publish"></a>

以下显示的是已注册和未注册的设备向除某些子主题之外的所有主题发布消息的示例。

------
#### [ Registered devices ]

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用与注册表中事物名称匹配的 ClientID 进行连接。它允许发布到所有以“department/”为前缀的主题，但不允许发布到“department/admins”子主题。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			],
			"Condition": {
				"Bool": {
					"iot:Connection.Thing.IsAttached": "true"
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/department/*"
			]
		},
		{
			"Effect": "Deny",
			"Action": [
				"iot:Publish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/department/admins"
			]
		}
	]
}
```

------
#### [ Unregistered devices ]

对于未在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用 clientID1、clientID2 或 clientID3 进行连接。它允许发布到所有以“department/”为前缀的主题，但不允许发布到“department/admins”子主题。

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/department/*"
            ]
        },
        {
            "Effect": "Deny",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/department/admins"
            ]
        }
    ]
}
```

------

## 拒绝接收来自主题名称的子主题的消息的策略
<a name="pub-sub-deny-receive"></a>

以下显示的是已注册和未注册的设备订阅除某些子主题之外具有特定前缀的主题，以及从此类主题接收消息的示例。

------
#### [ Registered devices ]

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用与注册表中事物名称匹配的 ClientID 进行连接。此策略允许设备订阅任何具有前缀“topic\$1prefix”的主题。通过`NotResource`在的语句中使用`iot:Receive`，我们允许设备接收来自设备已订阅的所有主题的消息，但以 “to prefix/restricted". For example, with this policy, devices can subscribe to "topic\$1prefix/topic1" and even "topic\$1prefix/restricted", however, they will only receive messages from the topic "topic\$1prefix/topic1" and no messages from the topic "topic\$1prefix/restricted pic\$1” 为前缀的主题除外。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			],
			"Condition": {
				"Bool": {
					"iot:Connection.Thing.IsAttached": "true"
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": "iot:Subscribe",
			"Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/topic_prefix/*"
		},
		{
			"Effect": "Allow",
			"Action": "iot:Receive",
			"NotResource": "arn:aws:iot:us-east-1:123456789012:topic/topic_prefix/restricted/*"
		}
	]
}
```

------
#### [ Unregistered devices ]

对于未在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用 clientID1、clientID2 或 clientID3 进行连接。此策略允许设备订阅任何具有前缀“topic\$1prefix”的主题。通过`NotResource`在的语句中使用`iot:Receive`，我们允许设备接收来自设备已订阅的所有主题的消息，但前缀为 “to prefix/restricted". For example, with this policy, devices can subscribe to "topic\$1prefix/topic1" and even "topic\$1prefix/restricted". However, they will only receive messages from the topic "topic\$1prefix/topic1" and no messages from the topic "topic\$1prefix/restricted pic\$1” 的主题除外。

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "iot:Subscribe",
            "Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/topic_prefix/*"
        },
        {
            "Effect": "Allow",
            "Action": "iot:Receive",
            "NotResource": "arn:aws:iot:us-east-1:123456789012:topic/topic_prefix/restricted/*"
        }
    ]
}
```

------

## 使用 MQTT 通配符订阅主题的策略
<a name="pub-sub-topic-wildcard"></a>

MQTT 通配符 \$1 和 \$1 被视为文字字符串，但在策略中使用时不会将其视为通配符。 AWS IoT Core 在 MQTT 中，\$1 和 \$1 仅在订阅主题筛选器时被视为通配符，但在所有其他上下文中均被视为文字字符串。我们建议您仅在仔细考虑后才将这些 MQTT 通配符用作 AWS IoT Core 策略的一部分。

以下显示了在策略中使用 MQTT 通配符的已注册和未注册事物的示例。 AWS IoT Core 这些通配符被视为文字字符串。

------
#### [ Registered devices ]

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用与注册表中事物名称匹配的 ClientID 进行连接。此策略允许设备订阅主题“部门/\$1/员工”和“位置/\$1”。由于 \$1 和 \$1 在 AWS IoT Core 策略中被视为文字字符串，因此设备可以订阅主题 “部门/\$1/员工”，但也不能订阅主题 “”。department/engineering/employees". Similarly, devices can subscribe to the topic "location/\$1" but not to the topic "location/Seattle". However, once the device subscribes to the topic "department/\$1/employees", the policy will allow them to receive messages from the topic "department/engineering/employees". Similarly, once the device subscribes to the topic "location/\$1", they will receive messages from the topic "location/Seattle

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
			],
			"Condition": {
				"Bool": {
					"iot:Connection.Thing.IsAttached": "true"
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": "iot:Subscribe",
			"Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/department/+/employees"
		},
		{
			"Effect": "Allow",
			"Action": "iot:Subscribe",
			"Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/location/#"
		},
		{
			"Effect": "Allow",
			"Action": "iot:Receive",
			"Resource": "arn:aws:iot:us-east-1:123456789012:topic/*"
		}
	]
}
```

------
#### [ Unregistered devices ]

对于未在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用 clientID1、clientID2 或 clientID3 进行连接。此策略允许设备订阅主题“部门/\$1/员工”和“位置/\$1”。由于 \$1 和 \$1 在 AWS IoT Core 策略中被视为文字字符串，因此设备可以订阅主题 “部门/\$1/员工”，但也不能订阅主题 “”。department/engineering/employees". Similarly, devices can subscribe to the topic "location/\$1" but not "location/Seattle". However, once the device subscribes to the topic "department/\$1/employees", the policy will allow them to receive messages from the topic "department/engineering/employees". Similarly, once the device subscribes to the topic "location/\$1", they will receive messages from the topic "location/Seattle

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/clientId1",
                "arn:aws:iot:us-east-1:123456789012:client/clientId2",
                "arn:aws:iot:us-east-1:123456789012:client/clientId3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "iot:Subscribe",
            "Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/department/+/employees"
        },
        {
            "Effect": "Allow",
            "Action": "iot:Subscribe",
            "Resource": "arn:aws:iot:us-east-1:123456789012:topicfilter/location/#"
        },
        {
            "Effect": "Allow",
            "Action": "iot:Receive",
            "Resource": "arn:aws:iot:us-east-1:123456789012:topic/*"
        }
    ]
}
```

------

## 适用于 HTTP 和 WebSocket 客户端的策略
<a name="pub-sub-policy-cognito"></a>

当你通过 HTTP 或 WebSocket 协议连接时，你就是在使用签名版本 4 和 Amazon Cognito 进行身份验证。Amazon Cognito Identity 可以是经过身份验证的，也可以是未经身份验证的。经过身份验证的身份属于已通过任何受支持的身份提供商进行身份验证的用户。未经身份验证的身份通常属于未使用身份提供商进行身份验证的来宾用户。Amazon Cognito 提供了唯一标识符和 AWS 凭证来支持未经身份验证的身份。有关更多信息，请参阅 [使用 Amazon Cognito Identity 的授权](cog-iot-policies.md)。

对于以下操作， AWS IoT Core 使用通过 API 附加到 Amazon Cognito 身份的 AWS IoT Core `AttachPolicy`策略。这将缩小附加到由经过身份验证的身份组成的 Amazon Cognito Identity 池的权限范围。
+ `iot:Connect`
+ `iot:Publish`
+ `iot:Subscribe`
+ `iot:Receive`
+ `iot:GetThingShadow`
+ `iot:UpdateThingShadow`
+ `iot:DeleteThingShadow`

这就表示，Amazon Cognito Identity 需要从 IAM 角色策略和 AWS IoT Core 策略获得权限。您可以通过 API 将 IAM 角色策略附加到池中，将 AWS IoT Core 策略附加到 Amazon Cognito 身份。 AWS IoT Core `AttachPolicy`

经过身份验证和未经身份验证的用户是不同的身份类型。如果您未将 AWS IoT 策略附加到 Amazon Cognito Identity，则经过身份验证的用户将无法在中进行授权， AWS IoT 并且无法访问 AWS IoT 资源和操作。

**注意**  
对于其他 AWS IoT Core 操作或未经身份验证的身份， AWS IoT Core 不会缩小附加到 Amazon Cognito 身份池角色的权限范围。无论是对于经过身份验证的身份还是未经过身份验证的身份，这都是我们建议附加到 Amazon Cognito 池角色的最宽松的策略。

**HTTP**

要允许未经过身份验证的 Amazon Cognito Identity 通过 HTTP 向特定于 Amazon Cognito Identity 的主题发布消息，请将以下 IAM 策略附加到 Amazon Cognito Identity 池角色：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/${cognito-identity.amazonaws.com:sub}"
            ]
        }
    ]
}
```

要允许经过身份验证的用户，请使用 API 将上述策略附加到 Amazon Cognito 身份池角色和亚马逊 Cognito 身份。 AWS IoT Core [AttachPolicy](https://docs.aws.amazon.com//iot/latest/apireference/API_AttachPolicy.html)

**注意**  
在授权 Amazon Cognito 身份时 AWS IoT Core ，会考虑这两个策略并授予指定的最低权限。仅当两个策略都允许请求的操作时，才允许操作。如果任一策略不允许某项操作，则该操作未经授权。

**MQTT**

要允许未经身份验证的 Amazon Cognito 身份发布有关您账户中特定 WebSocket 于亚马逊 Cognito 身份的主题的 MQTT 消息，请将以下 IAM 策略附加到 Amazon Cognito 身份池角色：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${cognito-identity.amazonaws.com:sub}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${cognito-identity.amazonaws.com:sub}"]
        }
    ]
}
```

要允许经过身份验证的用户，请使用 API 将上述策略附加到 Amazon Cognito 身份池角色和亚马逊 Cognito 身份。 AWS IoT Core [AttachPolicy](https://docs.aws.amazon.com//iot/latest/apireference/API_AttachPolicy.html)

**注意**  
在授权 Amazon Cognito 身份时 AWS IoT Core ，会同时考虑两者并授予指定的最低权限。仅当两个策略都允许请求的操作时，才允许操作。如果任一策略不允许某项操作，则该操作未经授权。

# 连接和发布策略示例
<a name="connect-and-pub"></a>

对于在注册 AWS IoT Core 表中注册为事物的设备，以下策略授予 AWS IoT Core 使用与事物名称匹配的客户端 ID 进行连接的权限，并限制设备只能在客户端 ID 或事物名称特定的 MQTT 主题上发布。要成功连接，必须在注册 AWS IoT Core 表中注册事物名称，并使用附加到事物的身份或委托人进行身份验证：

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topic/${iot:Connection.Thing.ThingName}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
      ]
    }
  ]
}
```

对于未在注册 AWS IoT Core 表中注册为事物的设备，以下策略授予 AWS IoT Core 使用客户端 ID 连接的权限，`client1`并限制设备只能在特定于客户的 MQTT 主题上发布：

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topic/${iot:ClientId}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:client/client1"
      ]
    }
  ]
}
```

# 保留的消息策略示例
<a name="retained-message-policy-examples"></a>

使用[保留的消息](mqtt.md#mqtt-retain)需要具体策略。保留的消息是在设置了 RETAIN 标志并由 AWS IoT Core存储的情况下发布的 MQTT 消息。本节介绍了允许常见使用保留消息的策略示例。

**Topics**
+ [连接和发布保留消息的策略](#retained-message-policy-examples-publish)
+ [连接和发布保留的 Will 消息的策略](#retained-message-policy-examples-publish-lwt)
+ [列出和获取保留消息的策略](#retained-message-policy-examples-list-get)

## 连接和发布保留消息的策略
<a name="retained-message-policy-examples-publish"></a>

对于要发布保留消息的设备，设备必须能够连接、发布（任何 MQTT 消息）和发布 MQTT 保留的消息。以下策略为主题授予了这些权限：`device/sample/configuration` 到客户端 **device1**。有关授予连接权限的另一个示例，请参阅 [连接和发布策略示例](connect-and-pub.md)。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/device1"
			]
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish",
				"iot:RetainPublish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/device/sample/configuration"
			]
		}
	]
}
```

## 连接和发布保留的 Will 消息的策略
<a name="retained-message-policy-examples-publish-lwt"></a>

客户端可以配置一条消息，该消息 AWS IoT Core 将在客户端意外断开连接时发布。MQTT 称这样的消息为 [*Will*消息](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html#_Will_Flag)。客户端必须在连接权限中添加附加条件才能包含这些条件。

以下策略文档授予所有客户端连接和发布由主题、`will` 标识的 Will 消息的权限， AWS IoT Core 也将保留。

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"iot:Connect"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:client/device1"
			],
			"Condition": {
				"ForAllValues:StringEquals": {
					"iot:ConnectAttributes": [
						"LastWill"
					]
				}
			}
		},
		{
			"Effect": "Allow",
			"Action": [
				"iot:Publish",
				"iot:RetainPublish"
			],
			"Resource": [
				"arn:aws:iot:us-east-1:123456789012:topic/will"
			]
		}
	]
}
```

## 列出和获取保留消息的策略
<a name="retained-message-policy-examples-list-get"></a>

服务和应用程序可以通过调用 [https://docs.aws.amazon.com//iot/latest/apireference/API_iotdata_ListRetainedMessages.html](https://docs.aws.amazon.com//iot/latest/apireference/API_iotdata_ListRetainedMessages.html) 和 [https://docs.aws.amazon.com//iot/latest/apireference/API_iotdata_GetRetainedMessage.html](https://docs.aws.amazon.com//iot/latest/apireference/API_iotdata_GetRetainedMessage.html) 来访问保留的消息，而无需支持 MQTT 客户端。调用这些操作的服务和应用程序必须使用如下示例的策略进行授权。

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:ListRetainedMessages"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/device1"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:GetRetainedMessage"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/foo"
            ]
        }
    ]
}
```

# 证书策略示例
<a name="certificate-policy-examples"></a>

对于在注册 AWS IoT Core 表中注册的设备，以下策略授予 AWS IoT Core 使用与事物名称匹配的客户端 ID 进行连接的权限，以及向名称等于该设备用于进行自我身份验证`certificateId`的证书的主题发布的权限：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:CertificateId}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"]
        }
    ]
}
```

对于未在注册 AWS IoT Core 表中注册的设备，以下策略授予使用客户端 IDs、`client1``client2`、`client3`和 AWS IoT Core 进行连接的权限，以及发布到名称等于设备用于进行自我身份验证`certificateId`的证书的主题的权限：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:CertificateId}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1",
                "arn:aws:iot:us-east-1:123456789012:client/client2",
                "arn:aws:iot:us-east-1:123456789012:client/client3"
            ]
        }
    ]
}
```

对于在注册 AWS IoT Core 表中注册的设备，以下策略授予 AWS IoT Core 使用与事物名称匹配的客户端 ID 进行连接的权限，以及向名称等于该设备进行身份验证的证书主题`CommonName`字段的主题发布权限：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:Certificate.Subject.CommonName}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"]
        }
    ]
}
```

**注意**  
在此示例中，证书的使用者公用名用作主题标识符，并假设使用者公用名对于每个已注册的证书都是唯一的。如果证书在多个设备之间共享，则共享此证书的所有设备的使用者公用名将相同，因而允许从多个设备向同一主题发布权限（不推荐）。

对于未在注册 AWS IoT Core 表中注册的设备，以下策略授予 AWS IoT Core 与客户端 IDs、`client1``client2`、`client3`和进行连接的权限，以及向名称等于设备用于进行身份验证的证书主题`CommonName`字段的主题发布的权限：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:Certificate.Subject.CommonName}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1",
                "arn:aws:iot:us-east-1:123456789012:client/client2",
                "arn:aws:iot:us-east-1:123456789012:client/client3"
            ]
        }
    ]
}
```

**注意**  
在此示例中，证书的使用者公用名用作主题标识符，并假设使用者公用名对于每个已注册的证书都是唯一的。如果证书在多个设备之间共享，则共享此证书的所有设备的使用者公用名将相同，因而允许从多个设备向同一主题发布权限（不推荐）。

对于在注册 AWS IoT Core 表中注册的设备，以下策略授予使用 AWS IoT Core 与事物名称匹配的客户端 ID 进行连接的权限，以及在用于对设备进行身份验证的证书的`Subject.CommonName.2`字段设置为`Administrator`：`admin/`

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/*"],
            "Condition": {
                "StringEquals": {
                    "iot:Certificate.Subject.CommonName.2": "Administrator"
            }
        }
        }
    ]
}
```

对于未在注册 AWS IoT Core 表中注册的设备，当用于对设备进行身份验证的证书的`Subject.CommonName.2`字段设置为`admin/`时 IDs `client1`，以下策略授予 AWS IoT Core 与客户端`client2`、`client3`和发布到名称前缀为的主题的权限：`Administrator`

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1",
                "arn:aws:iot:us-east-1:123456789012:client/client2",
                "arn:aws:iot:us-east-1:123456789012:client/client3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/*"],
            "Condition": {
                "StringEquals": {
                    "iot:Certificate.Subject.CommonName.2": "Administrator"
            }
        }
        }
    ]
}
```

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用其事物名称发布特定主题，该主题包括用于对设备进行身份验证的证书`ThingName`何时将其任何一个`Subject.CommonName`字段设置为`Administrator`：`admin/`

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/${iot:Connection.Thing.ThingName}"],
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:Certificate.Subject.CommonName.List": "Administrator"
            }
        }
        }
    ]
}
```

对于未在注册 AWS IoT Core 表中注册的设备，以下策略授予在用于对 AWS IoT Core 设备进行身份验证的证书的任意一个`Subject.CommonName`字段设置为`admin`时连接到客户端 IDs `client1``client2`、`client3`和向主题发布的权限`Administrator`：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1",
                "arn:aws:iot:us-east-1:123456789012:client/client2",
                "arn:aws:iot:us-east-1:123456789012:client/client3"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin"],
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "iot:Certificate.Subject.CommonName.List": "Administrator"
            }
        }
        }
    ]
}
```

# 事物策略示例
<a name="thing-policy-examples"></a>

如果用于进行身份验证的证书附加到正在评估策略的 AWS IoT Core 对象，则以下策略允许设备进行连接：

****  

```
{  
    "Version":"2012-10-17",		 	 	 
    "Statement":[
        {  
            "Effect":"Allow",
            "Action":["iot:Connect"],
            "Resource":[ "*" ],
            "Condition": {
                "Bool": {
                    "iot:Connection.Thing.IsAttached": ["true"]
            }
        }
        }
    ]
}
```

如果证书附加到具有特定事物类型的事物，并且该事物具有值为 `attributeValue` 的 `attributeName` 属性，则以下策略允许设备进行发布。有关事物策略变量的更多信息，请参阅[事物策略变量](thing-policy-variables.md)。

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": "arn:aws:iot:us-east-1:123456789012:topic/device/stats",
      "Condition": {
        "StringEquals": {
          "iot:Connection.Thing.Attributes[attributeName]": "attributeValue",
          "iot:Connection.Thing.ThingTypeName": "Thing_Type_Name"
        },
        "Bool": {
          "iot:Connection.Thing.IsAttached": "true"
        }
      }
    }
  ]
}
```

以下策略允许设备发布到以事物的属性开头的主题。如果设备证书与事物不关联，则将无法解析此变量，并将导致访问被拒绝错误。有关事物策略变量的更多信息，请参阅[事物策略变量](thing-policy-variables.md)。

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish"
      ],
      "Resource": "arn:aws:iot:us-east-1:123456789012:topic/${iot:Connection.Thing.Attributes[attributeName]}/*"
    }
  ]
}
```

# 基本任务策略示例
<a name="basic-jobs-example"></a>

此示例说明了任务目标所需的策略状态，任务目标是接收任务请求并与 AWS IoT通信任务执行状态的单个设备。

*us-west-2:57EXAMPLE833*替换为你的 AWS 区域、冒号字符 (:) 和你的 12 位 AWS 账户 数字，然后*uniqueThingName*替换为代表设备的事物资源的名称。 AWS IoT

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:client/uniqueThingName"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topic/test/dc/pubtopic",
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/events/job/*",
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/events/jobExecution/*",
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/things/uniqueThingName/jobs/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topicfilter/test/dc/subtopic",
                "arn:aws:iot:us-west-2:123456789012:topicfilter/$aws/events/jobExecution/*",
                "arn:aws:iot:us-west-2:123456789012:topicfilter/$aws/things/uniqueThingName/jobs/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topic/test/dc/subtopic",
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/things/uniqueThingName/jobs/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iotjobsdata:DescribeJobExecution",
                "iotjobsdata:GetPendingJobExecutions",
                "iotjobsdata:StartNextPendingJobExecution",
                "iotjobsdata:UpdateJobExecution"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topic/$aws/things/uniqueThingName"
            ]
        }
    ]
}
```

# 使用 Amazon Cognito Identity 的授权
<a name="cog-iot-policies"></a>

存在两种类型的 Amazon Cognito Identity：经过身份验证的身份和未经身份验证的身份。当您的应用程序支持未经身份验证的 Amazon Cognito Identity 时，将不会执行身份验证，因此您不知道用户的身份。

**未经身份验证的身份：**对于未经身份验证的 Amazon Cognito Identity，您可以通过将 IAM 角色附加到未经身份验证的身份池来授予权限。我们建议您仅授予对希望可供未知用户使用的那些资源的访问权限。

**重要**  
对于连接 AWS IoT Core至的未经身份验证的 Amazon Cognito 用户，我们建议您在 IAM 策略中允许访问非常有限的资源。

**经过身份验证的身份：**对于经过身份验证的 Amazon Cognito Identity，您需要在两个位置指定权限：
+ 将 IAM 策略附加到经过身份验证的 Amazon Cognito Identity 池和
+ 将 AWS IoT Core 策略附加到 Amazon Cognito 身份（经过身份验证的用户）。

## 未经身份验证和身份验证的 Amazon Cognito 用户连接到的策略示例 AWS IoT Core
<a name="cog-iot-policies-auth-unauth-examples"></a>

以下示例显示了 Amazon Cognito Identity 的 IAM 策略和物联网策略中的权限。经过身份验证的用户想要发布到设备特定的主题（例如device/DEVICE\$1ID/status）。

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/Client_ID"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/device/Device_ID/status"
            ]
        }
    ]
}
```

以下示例显示了 Amazon Cognito 未经身份验证角色的 IAM 策略中的权限。未经身份验证的用户希望发布到不需要身份验证的非设备特定主题。

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/non_device_specific_topic"
            ]
        }
    ]
}
```

## GitHub 例子
<a name="cog-iot-policies-github"></a>

以下示例 Web 应用程序 GitHub 展示了如何将对经过身份验证的用户的策略附件纳入用户注册和身份验证流程。
+ [MQTT publish/subscribe React Web 应用程序使用 AWS Amplify 和 AWS IoT Device SDK for JavaScript](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-cp)
+ [使用 AWS Amplify、和 Lambda 函数的 MQTT publish/subscribe React Web 应用程序 AWS IoT Device SDK for JavaScript](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-lambda)

Amplify 是一组工具和服务，可帮助您构建与 AWS 服务集成的网络和移动应用程序。有关 Amplify 的更多信息，请参阅 [Amplify Framework Documentation](https://docs.amplify.aws/)。

这两个示例都执行了以下步骤。

1. 用户注册账户时，应用程序会创建 Amazon Cognito 用户池和身份。

1. 用户进行身份验证时，应用程序将创建策略并将其附加到身份。这授予用户发布和订阅的权限。

1. 用户可以使用应用程序发布和订阅 MQTT 主题。

第一个示例直接在身份验证操作中使用 `AttachPolicy` API 操作。以下示例演示如何在使用 Amplify 和 AWS IoT Device SDK for JavaScript的反应 Web 应用程序中实现此 API。

```
function attachPolicy(id, policyName) {
    var Iot = new AWS.Iot({region: AWSConfiguration.region, apiVersion: AWSConfiguration.apiVersion, endpoint: AWSConfiguration.endpoint});
    var params = {policyName: policyName, target: id};

    console.log("Attach IoT Policy: " + policyName + " with cognito identity id: " + id);
    Iot.attachPolicy(params, function(err, data) {
         if (err) {
               if (err.code !== 'ResourceAlreadyExistsException') {
                  console.log(err);
               }
          }
         else  {
            console.log("Successfully attached policy with the identity", data);
         }
     });
}
```

此代码出现在 [AuthDisplay.js](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-cp/blob/d1c307b36357be934db9dda020140fa337709cd9/src/AuthDisplay.js#L45) 文件中。

第二个示例在 Lambda 函数中实现 `AttachPolicy` API 操作。以下示例说明 Lambda 如何使用此 API 调用。

```
iot.attachPolicy(params, function(err, data) {
     if (err) {
           if (err.code !== 'ResourceAlreadyExistsException') {
              console.log(err);
              res.json({error: err, url: req.url, body: req.body});
           }
      }
     else  {
        console.log(data);
        res.json({success: 'Create and attach policy call succeed!', url: req.url, body: req.body});
     }
 });
```

此代码出现在[app.js](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-lambda/blob/e493039581d2aff0faa3949086deead20a2c5385/amplify/backend/function/amplifyiotlambda/src/app.js#L50)文件的 `iot.GetPolicy` 函数中。

**注意**  
当您使用通过 Amazon Cognito 身份池获得的 AWS 证书调用该函数时，您的 Lambda 函数中的上下文对象包含的值为。`context.cognito_identity_id`有关更多信息，请参阅下列内容。  
[AWS Lambda Node.js 中的上下文对象](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html)
[AWS Lambda Python 中的上下文对象](https://docs.aws.amazon.com/lambda/latest/dg/python-context.html)
[AWS Lambda Ruby 中的上下文对象](https://docs.aws.amazon.com/lambda/latest/dg/ruby-context.html)
[AWS Lambda Java 中的上下文对象](https://docs.aws.amazon.com/lambda/latest/dg/java-context.html)
[AWS Lambda Go 中的上下文对象](https://docs.aws.amazon.com/lambda/latest/dg/golang-context.html)
[AWS Lambda C\$1 中的上下文对象](https://docs.aws.amazon.com/lambda/latest/dg/csharp-context.html)
[AWS Lambda 中的上下文对象 PowerShell](https://docs.aws.amazon.com/lambda/latest/dg/powershell-context.html)

# 使用 AWS IoT Core 凭证提供者授权直接调用 AWS 服务
<a name="authorizing-direct-aws"></a>

设备可以使用 X.509 证书通过 TLS 双向身份验证协议 AWS IoT Core 进行连接。其他 AWS 服务不支持基于证书的身份验证，但可以使用[AWS 签名版本 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) 格式的 AWS 凭据进行调用。[签名版本 4 算法](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)通常要求呼叫者拥有访问密钥 ID 和私有访问密钥。 AWS IoT Core 具有凭据提供程序，允许您使用内置的 [X.509 证书](x509-client-certs.html)作为对请求进行身份验证的唯一设备身份。 AWS 这样就不再需要将访问密钥 ID 和私有访问密钥存储在您的设备上。

凭证提供程序使用 X.509 证书对调用方进行身份验证并颁发具有有限权限的临时安全令牌。该令牌可用于对任何 AWS 请求进行签名和身份验证。这种验证 AWS 请求的方式要求您创建和配置一个 [AWS Identity and Access Management (IAM) 角色](https://docs.aws.amazon.com/service-authorization/latest/reference/id_roles.html)并将相应的 IAM 策略附加到该角色，以便证书提供者可以代表您担任该角色。有关 AWS IoT Core 和 IAM 的更多信息，请参阅 [的身份和访问管理 AWS IoT](security-iam.md)。

 AWS IoT 要求设备将[服务器名称指示 (SNI) 扩展](https://www.rfc-editor.org/rfc/rfc3546#section-3.1)发送到传输层安全 (TLS) 协议，并在`host_name`字段中提供完整的端点地址。`host_name` 字段必须包含您调用的端点，并且必须是：
+ `aws iot [describe-endpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-endpoint.html) --endpoint-type iot:CredentialProvider` 返回的 `endpointAddress`。

没有正确 `host_name` 值的设备尝试的连接将失败。

下图说明了凭证提供程序工作流程。

![\[AWS IoT Core 凭证提供者工作流程。\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/images/credentials-provider-diagram.png)


1.  AWS IoT Core 设备向凭证提供者发出 HTTPS 请求以获取安全令牌。该请求包括用于身份验证的设备 X.509 证书。

1. 凭证提供者将请求转发到 AWS IoT Core 身份验证和授权模块，以验证证书并验证设备是否有权请求安全令牌。

1. 如果证书有效且有权请求安全令牌，则 AWS IoT Core 身份验证和授权模块将返回成功。否则，它会向设备发送异常。

1. 成功验证证书之后，凭证提供程序将调用 [AWS Security Token Service (AWS STS)](https://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html) 来代入您为它创建的 IAM 角色。

1. AWS STS 向凭证提供者返回临时的有限权限安全令牌。

1. 凭证提供程序将该安全令牌返回给设备。

1. 设备使用安全令牌对签 AWS 名版本 4 的 AWS 请求进行签名。

1. 请求的服务调用 IAM 来验证签名并根据附加到您为凭证提供程序创建的 IAM 角色的访问策略授权请求。

1. 如果 IAM 成功验证签名并授权请求，则请求成功。否则，IAM 将发送异常。

下一节介绍如何使用证书来获取安全令牌。编写此内容时，假定您已[注册了设备](register-device.html)并为它[创建并激活了您自己的证书](device-certs-your-own.html)。

## 如何使用证书来获取安全令牌
<a name="authorizing-direct-aws.walkthrough"></a>

1. 配置凭证提供程序代表您的设备代入的 IAM 角色。将以下信任策略附加到该角色。  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Principal": {"Service": "credentials.iot.amazonaws.com"},
           "Action": "sts:AssumeRole"
       }
   }
   ```

   对于您要调用的每项 AWS 服务，请为该角色附加访问策略。凭证提供程序支持以下策略变量：
   + `credentials-iot:ThingName`
   + `credentials-iot:ThingTypeName`
   + `credentials-iot:AwsCertificateId`

   当设备在向 AWS 服务发出的请求中提供了事物名称时，凭证提供程序会将 `credentials-iot:ThingName` 和 `credentials-iot:ThingTypeName` 作为上下文变量添加到安全令牌。如果设备没有在请求中提供事物名称，则凭证提供程序将提供 `credentials-iot:AwsCertificateId` 作为上下文变量。您将事物名称作为 `x-amzn-iot-thingname` HTTP 请求标头的值进行传递。

   这三个变量仅适用于 IAM 策略，而不适用于 AWS IoT Core 策略。

1. 确保执行下一步（创建角色别名）的用户有权将新创建的角色传递给 AWS IoT Core。以下策略向 AWS 用户同时授`iam:PassRole`予`iam:GetRole`和权限。`iam:GetRole` 权限可让用户获取有关您刚创建的角色的信息。该`iam:PassRole`权限允许用户将角色传递给其他 AWS 服务。  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Action": [
               "iam:GetRole",
               "iam:PassRole"
           ],
           "Resource": "arn:aws:iam::123456789012:role/your role name"
       }
   }
   ```

1. 创建 AWS IoT Core 角色别名。要直接呼叫 AWS 服务的设备必须知道在连接时要使用哪个角色 ARN。 AWS IoT Core对角色 ARN 进行硬编码并不是一个很好的解决方案，因为它需要您在角色 ARN 发生更改时更新设备。更好的解决方案是使用 `CreateRoleAlias` API 创建一个指向角色 ARN 的角色别名。如果角色 ARN 发生更改，您只需更新角色别名。无需在设备上进行任何更改。此 API 接受以下参数：  
`roleAlias`  
必需。一个标识角色别名的任意字符串。它充当角色别名数据模型中的主键。它包含 1-128 个字符，并且必须仅包含字母数字字符以及 =、@ 和 - 符号。允许大写和小写字母字符。角色别名名称区分大小写。  
`roleArn`  
必需。角色别名所指向的角色的 ARN。  
`credentialDurationSeconds`  
可选。凭证有效的时间长度（以秒为单位）。最小值为 900 秒（15 分钟）。最大值为 43200 秒（12 小时）。默认值为 3600 秒（1 小时）。  
 AWS IoT Core 凭证提供者可以颁发最长有效期为 43,200 秒（12 小时）的证书。凭证的有效期长达 12 小时，有助于通过将凭证缓存更长时间来减少对凭证提供程序的调用次数。  
`credentialDurationSeconds` 值必须小于或等于角色别名引用的 IAM 角色的最长会话持续时间。有关更多信息，请参阅《Identity [and Access Managem AWS ent 用户指南》中的修改角色最长会话时长 (AWS API)](https://docs.aws.amazon.com//IAM/latest/UserGuide/roles-managingrole-editing-api.html#roles-modify_max-session-duration-api)。

   相关此 API 的更多信息，请参阅 [CreateRoleAlias](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateRoleAlias.html)。

1. 将策略附加到设备证书。附加到设备证书的策略必须向设备授予代入角色的权限。您可以通过授予对角色别名执行 `iot:AssumeRoleWithCertificate` 操作的权限来做到这一点，如以下示例所示。  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iot:AssumeRoleWithCertificate",
               "Resource": "arn:aws:iot:us-east-1:123456789012:rolealias/your role alias"
           }
       ]
   }
   ```

1. 向凭证提供程序发出 HTTPS 请求来获取安全令牌。提供以下信息：
   + *Certificate*：由于这是使用 TLS 双向身份验证的 HTTP 请求，因此，您在发出请求时必须向客户端提供证书和私有密钥。使用与注册证书时相同的证书和私钥 AWS IoT Core。

     要确保您的设备正在与之通信 AWS IoT Core （而不是模拟它的服务），请参阅[服务器身份验证](x509-client-certs.html#server-authentication)，点击链接下载相应的 CA 证书，然后将其复制到您的设备上。
   + *RoleAlias*：您为证书提供者创建的角色别名的名称。角色别名区分大小写，并且必须与中创建的角色别名相匹配 AWS IoT Core。
   + *ThingName*: 您在注册事物时创建 AWS IoT Core 的事物名称。这作为 `x-amzn-iot-thingname` HTTP 标头的值进行传递。仅当您在 AWS IoT Core 或 IAM 策略中使用事物属性作为策略变量时，才需要此值。
**注意**  
您在*ThingName*中提供的`x-amzn-iot-thingname`必须与分配给证书的 Thin AWS IoT g 资源的名称相匹配。如果不匹配，则返回 403 错误。

   在中运行以下命令 AWS CLI 以获取您的凭据提供程序终端节点 AWS 账户。相关此 API 的更多信息，请参阅 [DescribeEndpoint](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeEndpoint.html)。有关启用 FIPS 的端点，请参阅 [AWS IoT Core- 凭证提供者端点](iot-connect-fips.md#iot-connect-fips-credential)。

   ```
   aws iot describe-endpoint --endpoint-type iot:CredentialProvider
   ```

   以下 JSON 对象是 **describe-endpoint** 命令的示例输出。它包含您用于请求安全令牌的 `endpointAddress`。

   ```
   {
       "endpointAddress": "your_aws_account_specific_prefix.credentials.iot.your region.amazonaws.com"
   }
   ```

   使用端点向凭证提供程序发出 HTTPS 请求以返回安全令牌。以下示例命令使用 `curl`，但您可以使用任何 HTTP 客户端。
**注意**  
Ro *leAlias* 名称区分大小写，并且必须与中创建的角色别名相匹配。 AWS IoT

   ```
   curl --cert your certificate --key your private key -H "x-amzn-iot-thingname: your thing name" --cacert AmazonRootCA1.pem https://your endpoint /role-aliases/your role alias/credentials
   ```

   此命令返回包含 `accessKeyId`、`secretAccessKey`、`sessionToken` 和过期的安全令牌对象。以下 JSON 对象是 `curl` 命令的示例输出。

   ```
       {"credentials":{"accessKeyId":"access key","secretAccessKey":"secret access key","sessionToken":"session token","expiration":"2018-01-18T09:18:06Z"}}
   ```

   然后，您可以使用`accessKeyId``secretAccessKey`、和`sessionToken`值对 AWS 服务请求进行签名。有关演 end-to-end示，请参阅*AWS 安全*博客上的 [“如何使用 AWS 凭据提供者博客文章来消除设备中对硬编码 AWS IoT 凭据的需求](https://aws.amazon.com/blogs/security/how-to-eliminate-the-need-for-hardcoded-aws-credentials-in-devices-by-using-the-aws-iot-credentials-provider/)”。

# 通过 IAM 跨账户访问
<a name="cross-account-access"></a>

AWS IoT Core 允许您允许委托人发布或订阅 AWS 账户 未归委托人所有的主题中定义的主题。您可以通过创建 IAM 策略和 IAM 角色并将策略附加到角色来配置跨账户访问。

首先，创建一个客户托管 IAM 策略（如[创建 IAM 策略](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies_create.html)中所述），就像您在 AWS 账户中为其他用户和证书创建策略一样。

对于在注册 AWS IoT Core 表中注册的设备，以下策略允许设备 AWS IoT Core 使用与设备的事物名称相匹配的客户端 ID 进行连接并发布到设备事物名称`my/topic/thing-name `所在的位置*thing-name*：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:Connection.Thing.ThingName}"
            ]
        }
    ]
}
```

对于未在注册 AWS IoT Core 表中注册的设备，以下策略允许设备使用在您的账户 (123456789012) `client1` 注册 AWS IoT Core 表中注册的事物名称来连接 AWS IoT Core 并发布到名称前缀为的客户端 ID 专用主题：`my/topic/`

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:client/client1"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:ClientId}"
            ]
        }
    ]
}
```

接下来，按照[创建向 IAM 用户委派权限的角色](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-user.html)中的步骤操作。输入要与之共享访问权限的 AWS 账户 的账户 ID。接下来是最后一步，请将您刚刚创建的策略附加到角色。如果您稍后需要修改要向其授予权限的 AWS ID，可使用以下信任策略格式执行操作：

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": { 
                "AWS": "arn:aws:iam::567890123456:user/MyUser"
        },
            "Action": "sts:AssumeRole"
        }
    ]
}
```