

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 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 應用程式和桌面應用程式，都會使用未驗證的身分，已驗證的身分甚至可以是輸入 CLI AWS IoT Core 命令的使用者。只有當身分具有授予這些 AWS IoT Core 操作許可的政策時，才能執行操作。

 AWS IoT Core 政策和 IAM 政策都與 搭配使用， AWS IoT Core 以控制身分 （也稱為*委託人*) 可執行的操作。您使用的政策類型取決於您用來進行身分驗證的身分類型 AWS IoT Core。

AWS IoT Core 操作分為兩個群組：
+ 控制平面 API 可讓您執行管理任務，例如建立或更新憑證、物件、規則等。
+ 資料平面 API 可讓您將資料傳送至 並從中接收資料 AWS IoT Core。

您使用的政策類型，取決於您正使用控制平面或資料平面 API。

下表說明身分類型、其使用的通訊協定以及可用於授權的政策類型。


**AWS IoT Core 資料平面 API 和政策類型**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/iot/latest/developerguide/iot-authorization.html)


**AWS IoT Core 控制平面 API 和政策類型**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 policy. AWS IoT Core policies 適用於該物件群組中的任何物件。若要讓 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 Training and Certification 網站上的 [Deep Dive to AWS IoT Core Authentication and Authorization](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 身分授權
](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`  
代表將連線的 MQTT 用戶端從 中斷連線的許可 AWS IoT Core。每次發出強制中斷連線用戶端的請求時，都會檢查 `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:Connect` 的許可，方能授予 `iot:Publish` 的許可。

`iot:Receive`  
代表從 接收訊息的許可 AWS IoT Core。每次在將訊息傳送至用戶端時，系統就會確認 `iot:Receive` 許可。由於每次交付都會檢查此許可，因此您可以用其來撤銷目前訂閱某主題的用戶端許可。

`iot:RetainPublish`  
代表發佈已設定 RETAIN 旗標之 MQTT 訊息的許可。  
您必須也授予 `iot:Publish` 的許可，方能授予 `iot:RetainPublish` 的許可。

`iot:Subscribe`  
代表主題篩選條件的訂閱許可。代理程式每次接收 SUBSCRIBE 請求，就會檢查此許可。可以使用此許可來允許用戶端訂閱與特定主題模式相符的主題。  
您必須也授予 `iot:Connect` 的許可，方能授予 `iot:Subscribe` 的許可。Device Shadow 政策動作

`iot:DeleteThingShadow`  
代表可刪除物件 Device Shadow 的許可。每次發出刪除物件 Device Shadow 內容的請求時，就會檢查一次 `iot:DeleteThingShadow` 許可。

`iot:GetThingShadow`  
代表可擷取物件 Device Shadow 的許可。每次發出擷取物件 Device Shadow 內容的請求時，就會檢查一次 `iot:GetThingShadow` 許可。

`iot:ListNamedShadowsForThing`  
代表可列出物件具名影子的許可。每次發出列出物件具名影子的請求時，就會檢查一次 `iot:ListNamedShadowsForThing` 許可。

`iot:UpdateThingShadow`  
代表可更新裝置影子的許可。每次發出更新物件 Device Shadow 內容的請求時，就會檢查一次 `iot:UpdateThingShadow` 許可。

**注意**  
任務執行政策動作僅適用於 HTTP TLS 端點。如果您使用 MQTT 端點，必須使用此主題上述所定義的 MQTT 政策動作。  
如需示範此情況的任務執行政策範例，請參閱可與 MQTT 通訊協定搭配使用的 [基本任務政策範例](basic-jobs-example.md)。任務執行 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 Resource Name (ARN)。所有資源 ARNs都遵循下列格式：

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

下表顯示要為每個動作類型指定的資源。ARN 範例適用於分區 `123456789012`中的帳戶 ID `aws`，以及區域 的特定 `us-east-1`。如需 ARNs，請參閱 AWS Identity and Access Management 《 使用者指南》中的 [Amazon Resource Name (ARNs)](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference-arns.html)。


| Action | Resource Type (資源類型) | 資源名稱 | 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 |  發佈已設定 RETAIN 旗標的主題  |  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` 政策動作來控制可連接的用戶端 ID。例如，此政策僅允許那些用戶端 ID 為 `clientid1` 的用戶端連接：

****  

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

**注意**  
不建議搭配 `Connect` 使用政策變數 `${iot:ClientId}`。沒有對 `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 與物件名稱相符。在此情況下，您會從用戶端 ID 取得物件名稱，該用戶端 ID 位於當物件連線時傳送的 MQTT `Connect` 訊息中 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 over WebSocket 通訊協定進行連線時可用。
+ `iot:Connection.Thing.ThingTypeName`

  當政策受到評估時，這可以解析為所屬物件相關的物件類型。MQTT/WebSocket 連線的用戶端 ID 必須與物件名稱相同。本政策變數僅在透過 MQTT 或是經 WebSocket 通訊協定的 MQTT 進行連線時可用。
+ `iot:Connection.Thing.Attributes[attributeName]`

  當政策受到評估時，這可以解析為所屬物件相關的特定屬性值。單一物件至多可具備 50 個屬性。每一屬性均可作為政策變數：`iot:Connection.Thing.Attributes[attributeName]`，其中 *attributeName* 為屬性名稱。MQTT/WebSocket 連線的用戶端 ID 必須與物件名稱相同。本政策變數僅在透過 MQTT 或是經 WebSocket 通訊協定的 MQTT 進行連線時可用。
+ `iot:Connection.Thing.IsAttached`

  `iot:Connection.Thing.IsAttached: ["true"]` 強制執行只有在 中註冊 AWS IoT 並連接到主體的裝置才能存取政策內的許可。如果裝置提供的憑證未連接到登錄檔中的 AWS IoT Core IoT 物件，您可以使用此變數來防止 AWS IoT Core 裝置連接到 。此變數具有 值，`true`或`false`指出連線物件使用 [AttachThingPrincipal](https://docs.aws.amazon.com/iot/latest/apireference/API_AttachThingPrincipal.html) API 連接到登錄檔中的憑證或 Amazon Cognito 身分。物件名稱作為用戶端 ID。

如果您的用戶端 ID 與您的物件名稱相符，或者您只將憑證連接到物件，則使用政策定義中的政策變數可以簡化政策管理。您可以使用物件政策變數定義單一政策，而不是為每個 IoT 物件建立個別政策。此政策可以動態套用至所有裝置。以下是顯示其運作方式的範例政策。如需詳細資訊，請參閱[將 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` 會顯示在回應內文中。若要取得憑證的相關資訊，請使用 [DescribeCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeCertificate.html) `certificateId`中的 。

## 發行者屬性
<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` 取代為第一個國家/地區的名稱。

您可以使用開頭為一的索引，要求第一個值以外的特定屬性值。例如，在 `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>

本主題提供如何使用憑證政策變數的詳細資訊。當您建立 AWS IoT Core 根據 X.509 憑證屬性授予許可的政策時，X.509 憑證政策變數至關重要。如果您的 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`、`X509v3 Issuer Alternative Name`、 `Subject`和 `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_tw/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/iot/latest/developerguide/use-policy-variables.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 憑證不包含特定的憑證屬性，但您的政策文件中使用了對應的憑證政策變數，則政策評估可能會導致非預期的行為。這是因為政策陳述式中不會評估缺少的政策變數。

Certificate 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。

防範混淆代理人問題的最有效方法是使用 `aws:SourceArn` 全域條件內容索引鍵，其中包含資源的完整 Amazon Resource Name (ARN)。對於 AWS IoT，您的 `aws:SourceArn` 必須符合格式：`arn:aws:iot:region:account-id:resource-type/resource-id`適用於資源特定許可或 `arn:aws:iot:region:account-id:*`。resource-id 可以是允許資源的名稱或 ID，也可以是允許資源 IDs的萬用字元陳述式。請確定該*區域*符合您的 AWS IoT 區域，且*帳戶 ID* 符合您的客戶帳戶 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 Security Token Service (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`請求的資源。

具有下列信任政策的角色只能由 IoT 主體 (`iot.amazonaws.com`) 擔任 中指定的佈建範本`SourceArn`。

****  

```
{
   "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。

具有下列信任政策的角色只能由 IoT 主體 (`iot.amazonaws.com`) 擔任 中指定的 CA 憑證`SourceArn`。

****  

```
{
   "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`來限制角色可以擔任哪些資源。不過，在註冊 CA 憑證的初始 [RegisterCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCACertificate.html) 呼叫期間，您沒有條件中要指定的 CA 憑證 ARN`aws:SourceArn`。

若要解決此問題，例如，若要將佈建角色信任政策指定給向 註冊的特定 CA 憑證 AWS IoT Core，您可以執行下列動作：
+ 首先，呼叫 [RegisterCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCACertificate.html) 而不提供 `RegistrationConfig` 參數。
+ 向 CA 憑證註冊後 AWS IoT Core，請呼叫 [UpdateCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateCACertificate.html)。

  在 UpdateCACertificate 呼叫中，提供 `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`。建立 IAM 角色以搭配 AWS IoT Core 登入資料提供者使用時，您必須在`aws:SourceArn`條件中包含可能需要擔任該角色之任何角色別名的 ARNs，藉此授權跨服務`sts:AssumeRole`請求。

具有下列信任政策的角色只能由 中指定之 roleAlias 的 AWS IoT Core 登入資料提供者 (`credentials.iot.amazonaws.com`) 主體擔任`SourceArn`。如果委託人嘗試擷取`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 登錄檔中註冊並連接到用於連線之主體的物件名稱：

**注意**  
對於已註冊的裝置，建議您使用 `Connect` 動作的[物件政策變數](thing-policy-variables.md)，並將物件附加至用於連線的主體。

****  

```
{
	"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 政策中指定要在連線訊息中使用的屬性，例如 `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"
                    ]
            }
        }
        }
    ]
}
```

下列政策只允許透過具有 `LastWill` 與主題 `"my/lastwill/topicName"` 的用戶端連接，而且只要其使用 `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 AWS IoT Core 用戶端、HTTP 或 WebSocket 連線至 。當您使用 MQTT 用戶端連接，必須使用 X.509 憑證進行驗證。當您透過 HTTP 或 WebSocket 通訊協定連接時，必須使用 Signature 第 4 版和 Amazon Cognito 進行驗證。

**注意**  
對於已註冊的裝置，建議您使用 `Connect` 動作的[物件政策變數](thing-policy-variables.md)，並將物件附加至用於連線的主體。

**Topics**
+ [

## 在 MQTT 和 AWS IoT Core 政策中使用萬用字元
](#pub-sub-policy-cert)
+ [

## 向/從特定主題發佈、訂閱及接收訊息的政策
](#pub-sub-specific-topic)
+ [

## 向/從具有特定前綴主題發佈、訂閱及接收訊息的政策
](#pub-sub-policy-specific-topic-prefix)
+ [

## 向/從各項裝置特定主題發佈、訂閱及接收訊息的政策
](#pub-sub-specific-topic-device)
+ [

## 向/從主題名稱中具有物件屬性的主題發佈、訂閱和接收訊息的政策
](#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 中，萬用字元 `+`和 `#` 用於 [MQTT 主題篩選條件](https://docs.aws.amazon.com/iot/latest/developerguide/topics.html#topicfilters)，以訂閱多個主題 name. AWS IoT Core policies 使用 `*` 和 `?`做為萬用字元，並遵循 [IAM 政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_grammar.html#policies-grammar-json)的慣例。在政策文件中，`*` 代表任意字元組合，`?` 則代表任何單一字元。在政策文件中，MQTT 萬用字元 `+` 和 `#` 視為沒有特殊含義的字元。若要在政策中的 `resource` 屬性描述多個主題名稱和主題篩選條件，請使用 `*` 和 `?` 萬用字元代替 MQTT 萬用字元。

當您選擇要在政策文件中使用的萬用字元時，請考慮該`*`字元不限於單一主題層級。`+` 字元僅限於 MQTT 主題篩選條件中的單一主題層級。要幫助將萬用字元規範限制為單一 MQTT 主題篩選條件層級，請考慮使用多個 `?` 字元。更多有關在政策資源中使用萬用字元的資訊以及它們比對的更多範例，請參閱[在資源 ARN 中使用萬用字元](https://docs.aws.amazon.com//IAM/latest/UserGuide/reference_policies_elements_resource.html#reference_policies_elements_resource_wildcards)。

下表顯示 MQTT 用戶端的 AWS IoT Core 政策中使用的不同萬用字元。


| 萬用字元 | 是 MQTT 萬用字元 | MQTT 中的範例 | 是 AWS IoT Core 政策萬用字元 | MQTT 用戶端 AWS IoT Core 政策中的範例 | 
| --- | --- | --- | --- | --- | 
| \$1 | 是 | some/\$1 | 否 | N/A | 
| \$1 | 是 | some/\$1/topic | 否 | 不適用 | 
| \$1 | 否 | N/A | 是 | `topicfilter/some/*/topic` `topicfilter/some/sensor*/topic`  | 
| ? | 否 | N/A | 是 |  `topic/some/?????/topic` `topicfilter/some/sensor???/topic`  | 

## 向/從特定主題發佈、訂閱及接收訊息的政策
<a name="pub-sub-specific-topic"></a>

以下範例顯示已註冊和未註冊裝置向/從名為 "some\$1specific\$1topic" 的主題發佈、訂閱和接收訊息的情形。這些範例也突顯 `Publish` 和 `Receive` 使用 "topic" 作為資源，以及 `Subscribe` 使用 "topicfilter" 作為資源。

------
#### [ 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"
            ]
        }
    ]
}
```

------

## 向/從具有特定前綴主題發佈、訂閱及接收訊息的政策
<a name="pub-sub-policy-specific-topic-prefix"></a>

以下範例顯示已註冊和未註冊裝置向/從具有 "topic\$1prefix" 前綴的主題發佈、訂閱和接收訊息的情形。

**注意**  
請注意，`*`在此範例中使用萬用字元。雖然在單一陳述式中提供多個主題名稱的許可`*`非常有用，但透過為裝置提供比所需更多的權限，可能會導致意外的後果。因此，我們建議您在仔細考慮`*`之後，才使用萬用字元。

------
#### [ 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*"
            ]
        }
    ]
}
```

------

## 向/從各項裝置特定主題發佈、訂閱及接收訊息的政策
<a name="pub-sub-specific-topic-device"></a>

以下範例顯示已註冊和未註冊裝置向/從特定裝置專屬的主題發佈、訂閱和接收訊息的情形。

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

對於在 AWS IoT Core 登錄檔中註冊的裝置，下列政策允許裝置使用與登錄檔中物件名稱相符的 clientId 進行連線。它提供向物件特定主題 (`sensor/device/${iot:Connection.Thing.ThingName}`) 進行發佈的許可，以及從物件特定主題 (`command/device/${iot:Connection.Thing.ThingName}`) 進行訂閱和接收的許可。如果登錄檔中的物件名稱是「thing1」，裝置將能夠發佈到主題「sensor/device/thing1」。裝置也可以訂閱主題「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，它將能夠發佈到主題 "sensor/device/clientId1"。裝置也可以從主題 訂閱和接收 `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}"
            ]
        }
    ]
}
```

------

## 向/從主題名稱中具有物件屬性的主題發佈、訂閱和接收訊息的政策
<a name="pub-sub-topic-attribute"></a>

以下範例顯示已註冊裝置向/從名稱含有物件屬性的主題發佈、訂閱和接收訊息的情形。

**注意**  
物件屬性僅存在於登錄檔中 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`，裝置將能夠發佈至主題「感應器/v1」，並從主題「命令/西雅圖」訂閱和接收。

****  

```
{
	"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" 的主題。藉由在 `iot:Receive` 的陳述式中使用，`NotResource`我們允許裝置接收所有來自其已訂閱主題的訊息，但前綴為 "topic\$1prefix/restricted" 的主題除外。例如在此政策中，裝置可以訂閱 "topic\$1prefix/topic1" 甚至 "topic\$1prefix/restricted"，但是它們只會接收來自 "opic\$1prefix/topic1" 主題的訊息，且不會接收來自 "topic\$1prefix/restricted" 主題的訊息。

****  

```
{
	"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" 的主題。藉由在 `iot:Receive` 的陳述式中使用 `NotResource`，我們允許裝置接收所有來自其已訂閱主題的訊息，但前綴為 "topic\$1prefix/restricted" 的主題除外。例如，使用此政策，裝置可以訂閱 "topic\$1prefix/topic1" 甚至 "topic\$1prefix/restricted"。不過，他們只會收到主題 "topic\$1prefix/topic1" 的訊息，而不會收到主題 "topic\$1prefix/restricted" 的訊息。

****  

```
{
    "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 政策的一部分。

以下顯示 AWS IoT Core 政策中使用 MQTT 萬用字元註冊和未註冊物件的範例。這些萬用字元會視為常值字串。

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

對於在 AWS IoT Core 登錄檔中註冊的裝置，下列政策允許裝置使用與登錄檔中物件名稱相符的 clientId 進行連線。此政策允許裝置訂閱 "department/\$1/employees" 和 "location/\$1" 主題。由於 \$1 和 \$1 在 AWS IoT Core 政策中被視為文字字串，裝置可以訂閱主題「department/\$1/employees」，但不能訂閱主題「department/engineering/employees」。同樣，裝置可以訂閱 "location/\$1" 主題，但不能訂閱 "location/Seattle" 主題。但是，一旦裝置訂閱了 "department/\$1/employees" 主題，此政策將允許其接收來自 "department/engineering/employees" 主題的訊息。同樣，一旦裝置訂閱了 "location/\$1" 主題，其也將接收來自 "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 進行連線。此政策允許裝置訂閱 "department/\$1/employees" 和 "location/\$1" 主題。由於 \$1 和 \$1 在 AWS IoT Core 政策中被視為文字字串，裝置可以訂閱主題「department/\$1/employees」，但不能訂閱主題「department/engineering/employees」。同樣，裝置可以訂閱 "location/\$1" 主題，但不能訂閱 "location/Seattle"。但是，一旦裝置訂閱了 "department/\$1/employees" 主題，此政策將允許其接收來自 "department/engineering/employees" 主題的訊息。同樣，一旦裝置訂閱了 "location/\$1" 主題，其也將接收來自 "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 通訊協定連接時，必須使用 Signature 第 4 版和 Amazon Cognito 進行驗證。Amazon Cognito 身分可以是已驗證或未驗證的身分。已驗證的身分屬於已由任何支援的身分提供者驗證的使用者。未驗證的身分通常屬於未向身分提供者驗證身分的訪客使用者。Amazon Cognito 提供唯一識別符和 AWS 登入資料，以支援未經驗證的身分。如需詳細資訊，請參閱[使用 Amazon Cognito 身分授權](cog-iot-policies.md)。

對於下列操作， AWS IoT Core 會使用透過 `AttachPolicy` API 連接到 Amazon Cognito 身分 AWS IoT Core 的政策。這會縮小連接到具有已驗證身分之 Amazon Cognito 身分集區的許可範圍。
+ `iot:Connect`
+ `iot:Publish`
+ `iot:Subscribe`
+ `iot:Receive`
+ `iot:GetThingShadow`
+ `iot:UpdateThingShadow`
+ `iot:DeleteThingShadow`

這表示 Amazon Cognito Identity 需要 IAM 角色政策和 AWS IoT Core 政策的許可。您可以透過 `AttachPolicy` API 將 IAM 角色政策連接至集區，並將 AWS IoT Core 政策連接至 Amazon Cognito Identity AWS IoT Core 。

已驗證和未驗證的使用者是不同的身分類型。如果您未將 AWS IoT 政策連接至 Amazon Cognito Identity，則已驗證的使用者在 中的授權會失敗 AWS IoT ，而且無法存取 AWS IoT 資源和動作。

**注意**  
對於其他 AWS IoT Core 操作或未經驗證的身分， AWS IoT Core 不會縮小連接到 Amazon Cognito 身分集區角色的許可範圍。對於已驗證和未驗證兩者的身分而言，這是我們針對連接至 Amazon Cognito 集區角色的政策，所提供的最寬容建議。

**HTTP**

若要允許未驗證 Amazon Cognito 身分透過 HTTP 對 Amazon Cognito 身分特定的主題發佈訊息，請將下列 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}"
            ]
        }
    ]
}
```

若要允許已驗證的使用者，請使用 AWS IoT Core [AttachPolicy](https://docs.aws.amazon.com//iot/latest/apireference/API_AttachPolicy.html) API 將上述政策連接至 Amazon Cognito 身分集區角色和 Amazon Cognito 身分。

**注意**  
授權 Amazon Cognito 身分時， AWS IoT Core 請考慮政策並授予指定的最低權限。只有在兩個政策都允許要求的動作時，才會允許執行動作。如果兩個政策都禁止動作，則該動作為未授權。

**MQTT**

若要允許未驗證 Amazon Cognito 身分透過 WebSocket 對您帳戶中 Amazon 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}"]
        }
    ]
}
```

若要允許已驗證的使用者，請使用 AWS IoT Core [AttachPolicy](https://docs.aws.amazon.com//iot/latest/apireference/API_AttachPolicy.html) API 將上述政策連接至 Amazon Cognito 身分集區角色和 Amazon Cognito 身分。

**注意**  
授權 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`並限制裝置在 clientID 特定的 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 旗標設定並存放的 MQTT 訊息 AWS IoT Core。本節提供允許保留訊息常見用途的政策範例。

**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 登錄檔中註冊的裝置，以下政策會授予許可，以 AWS IoT Core 使用用戶端 IDs、`client2`、 `client1``client3`和 連線至 ，以發佈至其名稱等於用於驗證裝置本身之憑證`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、`client2`、 `client1``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` 欄位設定為 `admin/`時，發佈至其名稱字首為 的主題`Administrator`：

****  

```
{
    "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/`時，下列政策會授予許可，以使用 AWS IoT Core 用戶端 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": {
                "StringEquals": {
                    "iot:Certificate.Subject.CommonName.2": "Administrator"
            }
        }
        }
    ]
}
```

對於在 AWS IoT Core 登錄檔中註冊的裝置，下列政策允許裝置使用其實物名稱發佈到特定主題，該主題包含 `admin/`，當用來驗證裝置的憑證將其任何一個`Subject.CommonName`欄位設定為 `ThingName`時，後面接著 `Administrator`：

****  

```
{
    "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 登錄檔中註冊的裝置，當用於驗證裝置的憑證將其任何一個`Subject.CommonName`欄位設定為 `admin`時`client1`，下列政策會授予許可，以 AWS IoT Core 使用用戶端 IDs `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"]
            }
        }
        }
    ]
}
```

下列政策在憑證連接至具有特定物件類型的物件，且該物件的 `attributeName` 屬性具有 `attributeValue` 值時，允許裝置發佈。如需物件政策變數的詳細資訊，請參閱[物件政策變數](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 身分授權
<a name="cog-iot-policies"></a>

有兩種類型的 Amazon Cognito 身分：未驗證和已驗證。如果您的應用程式支援未驗證 Amazon Cognito 身分，則不會執行身分驗證，因此您不知道使用者是誰。

**Unauthenticated Identities**：(未驗證的身分) 對於未驗證的 Amazon Cognito 身分，您可以將 IAM 角色連接至未驗證的身分集區來授予許可。建議只授予您想要提供給未知使用者使用之資源的存取權。

**重要**  
對於未驗證的 Amazon Cognito 使用者連線到 AWS IoT Core，我們建議您授予 IAM 政策中非常有限資源的存取權。

**Authenticated Identities** (已驗證的身分)：對於已驗證的 Amazon Cognito 身分，您需要在兩個位置指定許可：
+ 將 IAM 政策連接到已驗證的 Amazon Cognito 身分集區，
+ 將 AWS IoT Core 政策連接至 Amazon Cognito 身分 （已驗證的使用者）。

## 未驗證和驗證連線至 的 Amazon Cognito 使用者的政策範例 AWS IoT Core
<a name="cog-iot-policies-auth-unauth-examples"></a>

下列範例顯示在 IAM 政策與 Amazon Cognito 身分 IoT 政策中的許可。已驗證身分的使用者希望發佈到裝置特定主題 (例如 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>

GitHub 上的下列範例 Web 應用程式，展示如何將已驗證使用者的政策附件合併到使用者註冊和身分驗證程序中。
+ [MQTT 使用 AWS Amplify 和 發佈/訂閱 React Web 應用程式 適用於 JavaScript 的 AWS IoT Device SDK](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-cp)
+ [MQTT 使用 AWS Amplify、 適用於 JavaScript 的 AWS IoT Device SDK和 Lambda 函數發佈/訂閱 React Web 應用程式](https://github.com/aws-samples/aws-amplify-react-iot-pub-sub-using-lambda)

Amplify 是一組工具和服務，可協助您建置與 AWS 服務整合的 Web 和行動應用程式。如需有關 Amplify 的詳細資訊，請參閱 [Amplify Framework 說明文件](https://docs.amplify.aws/)。

這兩個範例都會執行以下步驟。

1. 當使用者註冊帳戶時，應用程式會建立 Amazon Cognito 使用者集區和身分。

1. 當使用者進行身分驗證時，應用程式會建立政策並將其連接至身分。這會為使用者提供發佈和訂閱許可。

1. 使用者可以使用應用程式來發佈和訂閱 MQTT 主題。

第一個範例在身分驗證操作中直接使用 `AttachPolicy` API 操作。下面的範例示範如何在使用 Amplify 和 適用於 JavaScript 的 AWS IoT Device SDK的 React 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 Identity Pools 取得的 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 憑證， AWS IoT Core 使用 TLS 交互身分驗證通訊協定連線至 。 AWS 其他服務不支援以憑證為基礎的身分驗證，但可以使用 [AWS Signature 第 4 版格式](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)的 AWS 登入資料來呼叫。Signature [第 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)項目傳送至 Transport Layer Security (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_tw/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 ServiceAWS STS](https://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html) 來擔任您為該憑證建立的 IAM 角色。

1. AWS STS 會傳回臨時、有限權限的安全字符給登入資料提供者。

1. 憑證提供者傳回安全性字符到裝置。

1. 裝置使用安全字符來簽署 Signature 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的權限。下列政策會將 `iam:GetRole`和 `iam:PassRole`許可提供給 AWS 使用者。`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 分鐘)。最高值為 43,200 秒 (12 小時)。預設值為 3,600 秒 (1 小時)。  
 AWS IoT Core 登入資料提供者可以發出生命週期上限為 43，200 秒 (12 小時） 的登入資料。讓憑證有效時間長達 12 小時，有助於藉由快取憑證更長的時間，減少呼叫憑證提供者的次數。  
`credentialDurationSeconds` 值必須小於或等於該角色別名參考的 IAM 角色最大工作階段持續時間。如需詳細資訊，請參閱 Identity and Access Management 使用者指南中的 AWS [修改角色最長工作階段持續時間 (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 請求，以取得安全性字符。請提供下列資訊：
   + *憑證*：因為這是一個對 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 政策中的政策變數時，才需要此值。
**注意**  
您在 `x-amzn-iot-thingname` 中提供的 *ThingName* 必須符合指派給憑證的 AWS IoT 物件資源。如果不符合，則會傳回 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 用戶端。
**注意**  
*roleAlias* 名稱區分大小寫，且必須符合在其中建立的角色別名 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 政策](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies_create.html)中所述建立客戶受管的 IAM 政策，如同為 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) AWS IoT Core 登錄檔中`client1`註冊的物件名稱來連線至 ， 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"
        }
    ]
}
```