

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

# 使用 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 Identity （已驗證的使用者）。

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

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