

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

# 使用 API Gateway 資源政策來控制對 REST API 的存取
<a name="apigateway-resource-policies"></a>

Amazon API Gateway *資源政策*為連接到 API 的 JSON 政策文件，以控制指定的委託人 (通常是 IAM 角色或群組) 是否可以叫用 API。您可以使用 API Gateway 資源政策，允許您的 API 由以下來源安全地呼叫：
+ 來自指定 AWS 帳戶的使用者。
+ 指定來源 IP 地址範圍或 CIDR 區塊。
+ 指定 Virtual Private Cloud (VPC) 或 VPC 端點 (在任何帳戶)。

您可以使用 、 AWS CLI 或 AWS SDKs AWS 管理主控台，在 API Gateway 中連接任何 API 端點類型的資源政策。處理[私有 API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-apis.html) 時，您可以將資源政策與 VPC 端點政策搭配使用，藉此控制能具備存取權限的委託人，以及其可存取的資源和動作。如需詳細資訊，請參閱[在 API Gateway 中使用私有 API 的 VPC 端點政策](apigateway-vpc-endpoint-policies.md)。

 API Gateway 資源政策與 IAM 身分政策不同。IAM 身分政策會連接到 IAM 使用者、群組或角色，並定義這些身分能對哪些資源執行什麼動作。API Gateway 資源政策連接至資源。您可以使用 API Gateway 資源政策搭配 IAM 政策。如需更多詳細資訊，請參閱 [以身份為基礎和以資源為基礎的政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html)。

**Topics**
+ [

# Amazon API Gateway 的存取原則語言概觀
](apigateway-control-access-policy-language-overview.md)
+ [

# API Gateway 資源政策如何影響授權工作流程
](apigateway-authorization-flow.md)
+ [

# API Gateway 資源政策範例
](apigateway-resource-policies-examples.md)
+ [

# 建立 API Gateway 資源政策並連接至 API
](apigateway-resource-policies-create-attach.md)
+ [

# AWS 可用於 API Gateway 資源政策的條件索引鍵
](apigateway-resource-policies-aws-condition-keys.md)

# Amazon API Gateway 的存取原則語言概觀
<a name="apigateway-control-access-policy-language-overview"></a>

本頁說明 Amazon API Gateway 資源政策中使用的基本元素。

資源政策是使用與 IAM 政策相同的語法來進行指定。如需完整的政策語言資訊，請參閱 *IAM 使用者指南*中的 [IAM 政策概觀](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)和 [AWS Identity and Access Management 政策參考](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html)。

如需有關 AWS 服務如何決定是否應允許或拒絕特定請求的資訊，請參閱[決定是否允許或拒絕請求](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow)。

## 存取政策中的常用元素
<a name="apigateway-common-elements-in-an-access-policy"></a>

就其最基本意義而言，資源政策包含下列元素：
+ **資源** – API 是您可允許或拒絕許可的 Amazon API Gateway 資源。在政策中，您可以使用 Amazon Resource Name (ARN) 來識別資源。您也可以使用縮寫語法，當您儲存資源政策時，API Gateway 語法會自動將它展開為完整 ARN。如需詳細資訊，請參閱 [API Gateway 資源政策範例](apigateway-resource-policies-examples.md)。

  如需完整 `Resource` 元素的格式，請參閱[在 API Gateway 中執行 API 之許可的資源格式](api-gateway-control-access-using-iam-policies-to-invoke-api.md#api-gateway-iam-policy-resource-format-for-executing-api)。
+ **動作** - 針對每個資源，Amazon API Gateway 皆支援一組操作。您可使用動作關鍵字，來識別允許 (或拒絕) 資源操作。

  例如，`execute-api:Invoke` 許可讓使用者在使用者請求時有權叫用 API。

  如需 `Action` 元素的格式，請參閱 [在 API Gateway 中執行 API 之許可的動作格式](api-gateway-control-access-using-iam-policies-to-invoke-api.md#api-gateway-iam-policy-action-format-for-executing-api)。
+ **效果** - 當使用者請求特定動作時會有什麼效果，它可以是 `Allow` 或 `Deny`。您也可以明確拒絕存取資源，您可能會這樣做，以確保使用者無法存取資源，即使另有其他政策授予存取。
**注意**  
「隱含拒絕」與「預設拒絕」是相同的。  
「隱含拒絕」與「明確拒絕」不同。如需詳細資訊，請參閱[預設拒絕與明確拒絕間的差異](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#AccessPolicyLanguage_Interplay)。
+ **委託人** - 允許存取陳述式中動作與資源的帳戶或使用者。在資源政策中，委託人是接收此許可的使用者或帳戶。

下列範例資源政策會顯示先前的常用政策元素。此政策會將指定*區域*中指定 *account-id* 下 API 的存取權，授與其來源 IP 地址是在地址區塊 *123.4.5.6/24* 中的任何使用者。如果使用者的來源 IP 不在範圍內，則政策會拒絕所有對 API 的存取。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-east-1:111111111111:*"
        },
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-east-1:111111111111:*",
            "Condition": {
                "NotIpAddress": {
                    "aws:SourceIp": "123.4.5.6/24"
                }
            }
        }
    ]
}
```

------

# API Gateway 資源政策如何影響授權工作流程
<a name="apigateway-authorization-flow"></a>

API Gateway 評估連接到您 API 的資源政策時，其結果會受到您為 API 定義的身分驗證類型所影響，如下節流程圖所示。

**Topics**
+ [

## 僅限 API Gateway 資源政策
](#apigateway-authorization-flow-resource-policy-only)
+ [

## Lambda 授權方和資源政策
](#apigateway-authorization-flow-lambda)
+ [

## IAM 身分驗證和資源政策
](#apigateway-authorization-flow-iam)
+ [

## Amazon Cognito 身分驗證和資源政策
](#apigateway-authorization-flow-cognito)
+ [

## 政策評估結果表
](#apigateway-resource-policies-iam-policies-interaction)

## 僅限 API Gateway 資源政策
<a name="apigateway-authorization-flow-resource-policy-only"></a>

在此工作流程中，API Gateway 資源政策連接到 API，但未替 API 定義身分驗證類型。評估政策涉及根據呼叫者的傳入條件來尋求明確允許。隱含拒絕或任何明確拒絕會導致拒絕呼叫者。

![\[僅限資源政策的授權流程。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/apigateway-auth-resource-policy-only.png)


以下是這種資源政策的範例。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-east-1:111111111111:api-id/",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ]
                }
            }
        }
    ]
}
```

------

## Lambda 授權方和資源政策
<a name="apigateway-authorization-flow-lambda"></a>

在此工作流程中，除了資源政策，也為 API 設定 Lambda 授權方。資源政策將以兩個階段評估。在呼叫 Lambda 授權方之前，API Gateway 會先評估政策並檢查是否有任何明確的拒絕。若有找到，會立即拒絕呼叫者存取。否則，會呼叫 Lambda 授權方，而它將會傳回[政策文件](api-gateway-lambda-authorizer-output.md)，並與資源政策一起評估。如果您的授權方使用快取，API Gateway 可能會傳回快取的政策文件。結果會根據[表 A](#apigateway-resource-policies-iam-policies-interaction) 來判斷。

以下資源政策範例僅允許來自 VPC 端點 ID 為 `vpce-1a2b3c4d` 之 VPC 端點的呼叫。在預先授權評估期間，只會允許範例中來自以下指定之 VPC 端點的呼叫前進並評估 Lambda 授權方。所有剩餘的呼叫都會遭到封鎖。如果您針對私有 API 使用自訂網域名稱，則此授權工作流程相同。

![\[資源政策和 Lambda 授權方的授權流程。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/apigateway-auth-lambda-resource-policy.png)


------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "arn:aws:execute-api:us-east-1:111111111111:api-id/"
            ],
            "Condition" : {
                "StringNotEquals": {
                    "aws:SourceVpce": "vpce-1a2b3c4d"
                }
            }
        }
    ]
}
```

------

## IAM 身分驗證和資源政策
<a name="apigateway-authorization-flow-iam"></a>

在此工作流程中，除了資源政策外，您也會為 API 設定 IAM 身分驗證。在您使用 IAM 服務對使用者進行身份驗證後，API 會評估連接到使用者的政策和資源政策。結果會根據發起人是位於 AWS 帳戶與 API 擁有者相同的 AWS 帳戶 還是單獨的 而有所不同。

如果發起人和 API 擁有者來自不同的帳戶，IAM 政策和資源政策都需明確允許發起人繼續。如需更多詳細資訊，請參閱[表 B](#apigateway-resource-policies-iam-policies-interaction)。

然而，如果發起人和 API 擁有者位於相同的 AWS 帳戶，則 IAM 使用者政策或資源政策必須明確允許發起人繼續。如需更多詳細資訊，請參閱[表 A](#apigateway-resource-policies-iam-policies-interaction)。

![\[資源政策和 IAM 驗證的授權流程。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/apigateway-auth-iam-resource-policy.png)


以下是跨帳戶資源政策的範例。假設 IAM 政策包含允許效果，則該資源政策僅允許來自 VPC ID 為 `vpc-2f09a348` 的 VPC 的呼叫。如需更多詳細資訊，請參閱[表 B](#apigateway-resource-policies-iam-policies-interaction)。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "arn:aws:execute-api:us-east-1:111111111111:api-id/"
            ],
            "Condition" : {
                "StringEquals": {
                    "aws:SourceVpc": "vpc-2f09a348"
                    }
            }
        }
    ]
}
```

------

## Amazon Cognito 身分驗證和資源政策
<a name="apigateway-authorization-flow-cognito"></a>

在此工作流程中，除了資源政策之外，還會為 API 設定 [Amazon Cognito 使用者集區](apigateway-integrate-with-cognito.md)。API Gateway 會先嘗試透過 Amazon Cognito 驗證發起人。這通常會透過發起人提供的 [JWT 字符](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html)來執行。如果身分驗證成功，則會獨立評估資源政策，並需要明確允許。拒絕或既不允許也不拒絕會產生拒絕。以下是可搭配 Amazon Cognito 使用者集區使用的資源政策範例。

![\[資源政策和 Amazon Cognito 授權方的授權流程。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/apigateway-auth-cognito-resource-policy.png)


以下是僅允許來自指定來源 IP 之呼叫的資源政策範例，其中假設 Amazon Cognito 身分驗證字符包含 Allow (允許)。如需更多詳細資訊，請參閱[表 B](#apigateway-resource-policies-iam-policies-interaction)。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-east-1:111111111111:api-id/",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ]
                }
            }
        }
    ]
}
```

------

## 政策評估結果表
<a name="apigateway-resource-policies-iam-policies-interaction"></a>

表 A 列出對 API Gateway API 的存取是由 IAM 政策或 Lambda 授權方以及 API Gateway 資源政策控制 (這兩者位於相同的 AWS 帳戶中) 時，所產生的行為。


| **IAM 政策 (或 Lambda 授權方)** | **API Gateway 資源政策** | **產生行為** | 
| --- | --- | --- | 
| Allow | Allow | Allow | 
| Allow | 不允許也不拒絕 | Allow | 
| Allow | 拒絕 | 明確拒絕 | 
| 不允許也不拒絕 | Allow | Allow | 
| 不允許也不拒絕 | 不允許也不拒絕 | 隱含拒絕 | 
| 不允許也不拒絕 | 拒絕 | 明確拒絕 | 
| 拒絕 | Allow | 明確拒絕 | 
| 拒絕 | 不允許也不拒絕 | 明確拒絕 | 
| 拒絕 | 拒絕 | 明確拒絕 | 

表 B 列出 API Gateway API 的存取是由 IAM 政策或 Amazon Cognito 使用者集區授權方和 API Gateway 資源政策控制時所產生的行為，這些政策位於不同位置 AWS 帳戶。如果其中一個無訊息 (不允許也不拒絕)，則會拒絕跨帳戶存取。這是因為跨帳戶存取權需要資源政策和 IAM 政策或 Amazon Cognito 使用者集區授權方明確授與存取權。


| **IAM 政策 (或 Amazon Cognito 使用者集區授權方)** | **API Gateway 資源政策** | **產生行為** | 
| --- | --- | --- | 
| Allow | Allow | Allow | 
| Allow | 不允許也不拒絕 | 隱含拒絕 | 
| Allow | 拒絕 | 明確拒絕 | 
| 不允許也不拒絕 | Allow | 隱含拒絕 | 
| 不允許也不拒絕 | 不允許也不拒絕 | 隱含拒絕 | 
| 不允許也不拒絕 | 拒絕 | 明確拒絕 | 
| 拒絕 | Allow | 明確拒絕 | 
| 拒絕 | 不允許也不拒絕 | 明確拒絕 | 
| 拒絕 | 拒絕 | 明確拒絕 | 

# API Gateway 資源政策範例
<a name="apigateway-resource-policies-examples"></a>

本頁面顯示 API Gateway 資源政策之一般使用案例的一些範例。

下列範例政策使用簡化的語法來指定 API 資源。這種簡化的語法是您可以參考 API 資源的縮寫方式，而不是指定完整的 Amazon Resource Name (ARN)。當您儲存政策時，API Gateway 會將縮寫的語法轉換為完整的 ARN。例如，您可以在資源政策中指定資源 `execute-api:/stage-name/GET/pets`。當您儲存資源政策時，API Gateway 會將資源轉換為 `arn:aws:execute-api:us-east-2:123456789012:aabbccddee/stage-name/GET/pets`。API Gateway 會使用目前的區域、 AWS 您的帳戶 ID 和與資源政策相關聯的 REST API ID 來建置完整的 ARN。您可以使用 `execute-api:/*` 來表示目前 API 中的所有階段、方法和路徑。如需存取原則語言的詳細資訊，請參閱 [Amazon API Gateway 的存取原則語言概觀](apigateway-control-access-policy-language-overview.md)。

**Topics**
+ [

## 範例：允許另一個 AWS 帳戶中的角色使用 API
](#apigateway-resource-policies-cross-account-example)
+ [

## 範例：拒絕根據來源 IP 地址或範圍的 API 流量
](#apigateway-resource-policies-source-ip-address-example)
+ [

## 範例：使用私有 API 時，根據來源 IP 位址或範圍拒絕 API 流量
](#apigateway-resource-policies-source-ip-address-vpc-example)
+ [

## 範例：允許以來源 VPC 或 VPC 端點為依據的私有 API 流量
](#apigateway-resource-policies-source-vpc-example)

## 範例：允許另一個 AWS 帳戶中的角色使用 API
<a name="apigateway-resource-policies-cross-account-example"></a>

下列範例資源政策會透過 [Signature 第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html)版 (SigV4) 或 [Signature 第 4a 版](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html#how-sigv4a-works) (SigV4a) 通訊協定，將一個 AWS 帳戶中的 API 存取權授予不同 AWS 帳戶中的兩個角色。具體而言， 所識別 AWS 帳戶的開發人員和管理員角色`account-id-2`會獲授予 `execute-api:Invoke`動作，以對您 AWS 帳戶中`pets`的資源 (API) 執行 `GET`動作。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::111122223333:role/developer",
                    "arn:aws:iam::111122223333:role/Admin"
                ]
            },
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/stage/GET/pets"
            ]
        }
    ]
}
```

------

## 範例：拒絕根據來源 IP 地址或範圍的 API 流量
<a name="apigateway-resource-policies-source-ip-address-example"></a>

以下範例資源政策會拒絕 (封鎖) 從兩個指定的來源 IP 位址區塊傳入 API 流量。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/*"
            ]
        },
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
               "execute-api:/*"
            ],
            "Condition" : {
                "IpAddress": {
                    "aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ]
                }
            }
        }
    ]
}
```

------

如果您使用任何 IAM 使用者政策或 API Gateway 資源政策來控制 API Gateway 或任何 API Gateway API 的存取權，請確認您的政策已更新並包含 IPv6 位址範圍。若政策未更新，因而無法處理 IPv6 位址，則可能在用戶端開始使用雙堆疊端點時，影響用戶端對 API Gateway 的存取。如需詳細資訊，請參閱[在 IAM 原則中使用 IPv6 地址](api-ref.md#api-reference-service-endpoints-dualstack-iam)。

## 範例：使用私有 API 時，根據來源 IP 位址或範圍拒絕 API 流量
<a name="apigateway-resource-policies-source-ip-address-vpc-example"></a>

以下範例資源政策會拒絕 (封鎖) 從兩個指定的來源 IP 位址區塊傳入 API 流量。使用私有 API 時，`execute-api` 的 VPC 端點會重新寫入原始來源 IP 位址。`aws:VpcSourceIp` 條件會根據原始請求者 IP 位址篩選請求。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/*"
            ]
        },
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
               "execute-api:/*"
            ],
            "Condition" : {
                "IpAddress": {
                    "aws:VpcSourceIp": ["192.0.2.0/24", "198.51.100.0/24"]
                }
            }
        }
    ]
}
```

------

## 範例：允許以來源 VPC 或 VPC 端點為依據的私有 API 流量
<a name="apigateway-resource-policies-source-vpc-example"></a>

以下範例資源政策僅允許來自指定的 Virtual Private Cloud (VPC) 或 VPC 端點的流量傳入私有 API。

此範例資源政策會指定來源 VPC：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/*"
            ]
        },
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/*"
            ],
            "Condition" : {
                "StringNotEquals": {
                   "aws:SourceVpc": "vpc-1a2b3c4d"
                }
            }
        }
    ]
}
```

------

此範例資源政策會指定來源 VPC 端點：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/*"
            ]
        },
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/*"
            ],
            "Condition" : {
                "StringNotEquals": {
                    "aws:SourceVpce": "vpce-1a2b3c4d"
                }
            }
        }
    ]
}
```

------

# 建立 API Gateway 資源政策並連接至 API
<a name="apigateway-resource-policies-create-attach"></a>

為了讓使用者透過呼叫 API 執行服務來存取您的 API，您必須建立 API Gateway 資源政策，並將政策連接到 API。當您將政策附加至 API，會將政策中的許可權套用至 API 中的方法。如果更新資源政策，您需要部署 API。

**Topics**
+ [

## 先決條件
](#apigateway-resource-policies-prerequisites)
+ [

## 將資源政策連接至 API Gateway API
](#apigateway-resource-policies-create-attach-procedure)
+ [

## 為資源政策進行疑難排解
](#apigateway-resource-policies-troubleshoot)

## 先決條件
<a name="apigateway-resource-policies-prerequisites"></a>

 若要更新 API Gateway 資源政策，您需要 `apigateway:UpdateRestApiPolicy` 許可和 `apigateway:PATCH` 許可。

對於邊緣最佳化的或區域 API，您可以在建立資源政策時或部署之後，將資源政策連接至 API。對於私有 API，您無法在沒有資源政策的情況下部署 API。如需詳細資訊，請參閱[API Gateway 中的私有 REST API](apigateway-private-apis.md)。

## 將資源政策連接至 API Gateway API
<a name="apigateway-resource-policies-create-attach-procedure"></a>

下列程序顯示如何將資源政策連接至 API Gateway API。

------
#### [ AWS 管理主控台 ]

**將資源政策連接至 API Gateway API**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇 REST API。

1. 在主導覽窗格中，選擇**資源政策**。

1. 選擇**建立政策**。

1. (選用) 選擇**選取範本**以產生範例政策。

   在範例政策中，預留位置位於雙大括號中 (`"{{placeholder}}"`)。將每個預留位置 (包括大括號) 取代為所需的資訊。

1. 如果您不使用其中一個範本範例，請輸入您的資源政策。

1. 選擇**儲存變更**。

如果先前已在 API Gateway 主控台中部署該 API，您將需要為資源政策重新部署 API，才能生效。

------
#### [ AWS CLI ]

若要使用 AWS CLI 建立新的 API 並連接資源政策，請使用下列 [create-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-rest-api.html) 命令：

```
aws apigateway create-rest-api \
    --name "api-name" \
    --policy "{\"jsonEscapedPolicyDocument\"}"
```

若要使用 AWS CLI 將資源政策連接至現有的 API，請使用下列 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令：

```
aws apigateway update-rest-api \
    --rest-api-id api-id \
    --patch-operations op=replace,path=/policy,value='"{\"jsonEscapedPolicyDocument\"}"'
```

您也可以將您的資源政策附加為不同的 `policy.json` 檔案，並將其包含在 [create-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-rest-api.html) 命令中。以下 [create-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-rest-api.html) 命令會建立具有資源政策的新 API：

```
aws apigateway create-rest-api \
    --name "api-name" \
    --policy file://policy.json
```

`policy.json` 是 API Gateway 資源政策，例如 [範例：拒絕根據來源 IP 地址或範圍的 API 流量](apigateway-resource-policies-examples.md#apigateway-resource-policies-source-ip-address-example)。

------
#### [ AWS CloudFormation ]

您可以使用 CloudFormation 建立具有資源政策的 API。下列範例會使用範例資源政策 [範例：拒絕根據來源 IP 地址或範圍的 API 流量](apigateway-resource-policies-examples.md#apigateway-resource-policies-source-ip-address-example) 建立 REST API。

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: testapi
      Policy:
        Statement:
          - Action: 'execute-api:Invoke'
            Effect: Allow
            Principal: '*'
            Resource: 'execute-api:/*'
          - Action: 'execute-api:Invoke'
            Effect: Deny
            Principal: '*'
            Resource: 'execute-api:/*'
            Condition:
              IpAddress: 
                'aws:SourceIp': ["192.0.2.0/24", "198.51.100.0/24" ]
        Version: 2012-10-17		 	 	 
  Resource:
    Type: 'AWS::ApiGateway::Resource'
    Properties:
      RestApiId: !Ref Api
      ParentId: !GetAtt Api.RootResourceId
      PathPart: 'helloworld'
  MethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref Resource
      HttpMethod: GET
      ApiKeyRequired: false
      AuthorizationType: NONE
      Integration:
        Type: MOCK
        RequestTemplates:
          application/json: '{"statusCode": 200}'
        IntegrationResponses:
          - StatusCode: 200
            ResponseTemplates:
              application/json: '{}'
      MethodResponses:
        - StatusCode: 200
          ResponseModels:
            application/json: 'Empty'
  ApiDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn:
      - MethodGet
    Properties:
      RestApiId: !Ref Api
      StageName: test
```

------

## 為資源政策進行疑難排解
<a name="apigateway-resource-policies-troubleshoot"></a>

下列疑難排解指引可能有助於解決您的資源政策問題。

### 我的 API 傳回 \$1"Message":"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-east-1:\$1\$1\$1\$1\$1\$1\$1\$1/\$1\$1\$1\$1/\$1\$1\$1\$1/"\$1
<a name="apigateway-resource-policies-troubleshoot-auth"></a>

在您的資源政策中，如果您將主體設定為 AWS 委託人，如下所示：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::111111111111:role/developer",
                    "arn:aws:iam::111111111111:role/Admin"
                ]
            },
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/stage/GET/pets"
            ]
        }
    ]
}
```

------

您必須對 API 中的每個方法使用 `AWS_IAM` 授權，否則您的 API 會傳回先前的錯誤訊息。如需有關如何為方法開啟 `AWS_IAM` 授權的詳細資訊，請參閱 [API Gateway 中 REST API 的方法](how-to-method-settings.md)。

### 我的資源政策未更新
<a name="apigateway-resource-policies-troubleshoot-deploy"></a>

 如果您在 API 建立後更新資源政策，您會需要部署 API 以在您連接更新的政策後傳播變更。單獨更新或儲存政策不會變更 API 的執行階段行為。如需部署 API 的詳細資訊，請參閱 [在 API Gateway 中部署 REST API](how-to-deploy-api.md)。

### 我的資源政策傳回下列錯誤：政策文件無效。請檢查政策語法，並確保主體有效。
<a name="apigateway-resource-policies-troubleshoot-invalid-principal"></a>

若要針對此錯誤進行疑難排解，建議您先檢查政策語法。如需詳細資訊，請參閱[Amazon API Gateway 的存取原則語言概觀](apigateway-control-access-policy-language-overview.md)。我們也建議您確認所有指定的主體是否有效，且尚未刪除。

此外，如果您的 API 位於[選擇加入區域](https://docs.aws.amazon.com/glossary/latest/reference/glos-chap.html?icmpid=docs_homepage_addtlrcs#optinregion)，請確認資源政策中的所有帳戶都已啟用區域。

# AWS 可用於 API Gateway 資源政策的條件索引鍵
<a name="apigateway-resource-policies-aws-condition-keys"></a>

下表包含 AWS 條件索引鍵，可用於 APIs Gateway 中每個授權類型的 API 資源政策。

如需 AWS 條件金鑰的詳細資訊，請參閱[AWS 全域條件內容金鑰](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)。


| **條件索引鍵** | **條件** | **需要 `AuthN`？** | **授權類型** | 
| --- | --- | --- | --- | 
| aws:CurrentTime | 無 | 否 | 全部 | 
| aws:EpochTime | 無 | 否 | 全部 | 
| aws:TokenIssueTime | 金鑰僅在使用臨時安全登入資料簽署的要求中才會出現。 | 是 | IAM | 
| aws:MultiFactorAuthPresent | 金鑰僅在使用臨時安全登入資料簽署的要求中才會出現。 | 是 | IAM | 
| aws:MultiFactorAuthAge | 金鑰僅在 MFA 存在於請求時才會出現。 | 是 | IAM | 
| aws:PrincipalAccount | 無 | 是 | IAM | 
| aws:PrincipalArn | 無 | 是 | IAM | 
| aws:PrincipalOrgID | 只有在委託人是組織的成員時，請求內容中才會包含此金鑰。 | 是 | IAM | 
| aws:PrincipalOrgPaths | 只有在委託人是組織的成員時，請求內容中才會包含此金鑰。 | 是 | IAM | 
| aws:PrincipalTag | 若委託人搭配連接標籤使用 IAM 使用者，此鍵會包含在請求內容中。其會針對委託人，使用具備連接標籤或工作階段標籤的 IAM 角色包含在其中。 | 是 | IAM | 
| aws:PrincipalType | 無 | 是 | IAM | 
| aws:Referer | 金鑰僅在 HTTP 標頭中的呼叫者提供值時才會出現。 | 否 | 全部 | 
| aws:SecureTransport | 無 | 否 | 全部 | 
| aws:SourceArn | 無 | 否 | 全部 | 
| aws:SourceIp | 無 | 否 | 全部 | 
| aws:SourceVpc | 此金鑰只能用於私有 API。 | 否 | 全部 | 
| aws:SourceVpce | 此金鑰只能用於私有 API。 | 否 | 全部 | 
| aws:VpcSourceIp | 此金鑰只能用於私有 API。 | 否 | 全部 | 
| aws:UserAgent | 金鑰僅在 HTTP 標頭中的呼叫者提供值時才會出現。 | 否 | 全部 | 
| aws:userid | 無 | 是 | IAM | 
| aws:username | 無 | 是 | IAM | 