

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

# Amazon API Gateway 身分型政策範例
<a name="security_iam_id-based-policy-examples"></a>

預設情況下，IAM 使用者和角色沒有建立或修改 API Gateway 資源的許可。他們也無法使用 AWS 管理主控台 AWS CLI或 AWS SDKs 執行任務。IAM 管理員必須建立 IAM 政策，授予使用者和角色在指定資源上執行特定 API 作業的所需許可。管理員接著必須將這些政策連接至需要這些許可的 IAM 使用者或群組。

如需有關如何建立 IAM 政策的資訊，請參閱*《IAM 使用者指南》*中[在 JSON 索引標籤上建立政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-json-editor)。如需有關 API Gateway 特定動作、資源和條件索引鍵的資訊，請參閱 [Amazon API Gateway Management 的動作、資源和條件索引鍵](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonapigatewaymanagement.html)和 [Amazon API Gateway Management V2 的動作、資源和條件索引鍵](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonapigatewaymanagementv2.html)。

**Topics**
+ [政策最佳實務](#security_iam_service-with-iam-policy-best-practices)
+ [允許使用者檢視他們自己的許可](#security_iam_id-based-policy-examples-view-own-permissions)
+ [簡易讀取許可](#api-gateway-policy-example-apigateway-general)
+ [僅建立 REQUEST 或 JWT 授權者](#security_iam_id-based-policy-examples-v2-import)
+ [要求停用預設 `execute-api` 端點](#security_iam_id-based-policy-examples-v2-endpoint-status)
+ [允許使用者僅建立或更新私有 REST API](#security_iam_id-based-policy-examples-private-api)
+ [要求 API 路由具有授權](#security_iam_id-based-policy-examples-require-authorization)
+ [防止使用者建立或更新 VPC 連結](#security_iam_id-based-policy-examples-deny-vpc-link)
+ [使用路由規則的範例政策](#security_iam_id-based-policy-examples-routing-mode)

## 政策最佳實務
<a name="security_iam_service-with-iam-policy-best-practices"></a>

身分型政策會判斷您帳戶中的某個人員是否可以建立、存取或刪除 API Gateway 資源。這些動作可能會讓您的 AWS 帳戶產生費用。當您建立或編輯身分型政策時，請遵循下列準則及建議事項：
+ **開始使用 AWS 受管政策並邁向最低權限許可** – 若要開始將許可授予您的使用者和工作負載，請使用將許可授予許多常見使用案例的 *AWS 受管政策*。它們可在您的 中使用 AWS 帳戶。我們建議您定義特定於使用案例 AWS 的客戶受管政策，以進一步減少許可。如需更多資訊，請參閱《*IAM 使用者指南*》中的 [AWS 受管政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies)或[任務職能的AWS 受管政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_job-functions.html)。
+ **套用最低權限許可** – 設定 IAM 政策的許可時，請僅授予執行任務所需的許可。為實現此目的，您可以定義在特定條件下可以對特定資源採取的動作，這也稱為*最低權限許可*。如需使用 IAM 套用許可的更多相關資訊，請參閱《*IAM 使用者指南*》中的 [IAM 中的政策和許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)。
+ **使用 IAM 政策中的條件進一步限制存取權** – 您可以將條件新增至政策，以限制動作和資源的存取。例如，您可以撰寫政策條件，指定必須使用 SSL 傳送所有請求。如果透過特定 等使用服務動作 AWS 服務，您也可以使用條件來授予其存取權 CloudFormation。如需詳細資訊，請參閱《*IAM 使用者指南*》中的 [IAM JSON 政策元素：條件](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html)。
+ **使用 IAM Access Analyzer 驗證 IAM 政策，確保許可安全且可正常運作** – IAM Access Analyzer 驗證新政策和現有政策，確保這些政策遵從 IAM 政策語言 (JSON) 和 IAM 最佳實務。IAM Access Analyzer 提供 100 多項政策檢查及切實可行的建議，可協助您撰寫安全且實用的政策。如需詳細資訊，請參閱《*IAM 使用者指南*》中的[使用 IAM Access Analyzer 驗證政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-validation.html)。
+ **需要多重要素驗證 (MFA)** – 如果您的案例需要 IAM 使用者或 中的根使用者 AWS 帳戶，請開啟 MFA 以提高安全性。如需在呼叫 API 操作時請求 MFA，請將 MFA 條件新增至您的政策。如需詳細資訊，請參閱《*IAM 使用者指南*》中的[透過 MFA 的安全 API 存取](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)。

如需 IAM 中最佳實務的相關資訊，請參閱《*IAM 使用者指南*》中的 [IAM 安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)。

## 允許使用者檢視他們自己的許可
<a name="security_iam_id-based-policy-examples-view-own-permissions"></a>

此範例會示範如何建立政策，允許 IAM 使用者檢視附加到他們使用者身分的內嵌及受管政策。此政策包含在主控台或使用 或 AWS CLI AWS API 以程式設計方式完成此動作的許可。

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ViewOwnUserInfo",
            "Effect": "Allow",
            "Action": [
                "iam:GetUserPolicy",
                "iam:ListGroupsForUser",
                "iam:ListAttachedUserPolicies",
                "iam:ListUserPolicies",
                "iam:GetUser"
            ],
            "Resource": ["arn:aws:iam::*:user/${aws:username}"]
        },
        {
            "Sid": "NavigateInConsole",
            "Effect": "Allow",
            "Action": [
                "iam:GetGroupPolicy",
                "iam:GetPolicyVersion",
                "iam:GetPolicy",
                "iam:ListAttachedGroupPolicies",
                "iam:ListGroupPolicies",
                "iam:ListPolicyVersions",
                "iam:ListPolicies",
                "iam:ListUsers"
            ],
            "Resource": "*"
        }
    ]
}
```

## 簡易讀取許可
<a name="api-gateway-policy-example-apigateway-general"></a>

此範例政策提供使用者許可，以取得在 us-east-1 `a123456789` AWS 區域中識別符 之 HTTP 或 WebSocket API 所有資源的相關資訊。資源 `arn:aws:apigateway:{{us-east-1}}::/apis/a123456789/*` 包括 API 的所有子資源，例如授權者和部署。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "apigateway:GET"
      ],
      "Resource": [
        "arn:aws:apigateway:{{us-east-1}}::/apis/a123456789/*"
      ]
    }
  ]
}
```

------

## 僅建立 REQUEST 或 JWT 授權者
<a name="security_iam_id-based-policy-examples-v2-import"></a>

此範例政策允許使用者僅使用 `REQUEST` 或 `JWT` 授權者建立 API，包括透過[匯入](https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis.html#ImportApi)。在政策的 `Resource` 區段中，`arn:aws:apigateway:us-east-1::/apis/??????????` 要求資源最多有 10 個字元，其中排除 API 的子資源。本範例會在 `ForAllValues` 區段中使用 `Condition`，因為使用者可以透過匯入 API 來一次建立多個授權者。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "OnlyAllowSomeAuthorizerTypes",
      "Effect": "Allow",
      "Action": [
        "apigateway:PUT",
        "apigateway:POST",
        "apigateway:PATCH"
      ],
      "Resource": [
        "arn:aws:apigateway:us-east-1::/apis",
        "arn:aws:apigateway:us-east-1::/apis/??????????",
        "arn:aws:apigateway:us-east-1::/apis/*/authorizers",
        "arn:aws:apigateway:us-east-1::/apis/*/authorizers/*"
      ],
      "Condition": {
        "ForAllValues:StringEqualsIfExists": {
          "apigateway:Request/AuthorizerType": [
            "REQUEST",
            "JWT"
          ]
        }
      }
    }
  ]
}
```

------

## 要求停用預設 `execute-api` 端點
<a name="security_iam_id-based-policy-examples-v2-endpoint-status"></a>

 此範例政策允許使用者建立、更新或匯入 API，而且要求 `DisableExecuteApiEndpoint` 為 `true`。如果 `DisableExecuteApiEndpoint` 為 `true`，則用戶端無法使用預設 `execute-api` 端點來叫用 API。

我們使用 `BoolIfExists` 條件來處理呼叫以更新沒有填入 `DisableExecuteApiEndpoint` 條件索引鍵的 API。當使用者嘗試建立或匯入 API 時，一律會填入 `DisableExecuteApiEndpoint` 條件索引鍵。

由於 `apis/*` 資源也會擷取子資源 (例如授權者或方法)，所以我們明確地將其範圍設定為僅使用 `Deny` 陳述式的 API。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DisableExecuteApiEndpoint",
      "Effect": "Allow",
      "Action": [
        "apigateway:PATCH",
        "apigateway:POST",
        "apigateway:PUT"
      ],
      "Resource": [
        "arn:aws:apigateway:us-east-1::/apis",
        "arn:aws:apigateway:us-east-1::/apis/*"
      ],
      "Condition": {
        "BoolIfExists": {
          "apigateway:Request/DisableExecuteApiEndpoint": true
        }
      }
    },
    {
      "Sid": "ScopeDownToJustApis",
      "Effect": "Deny",
      "Action": [
        "apigateway:PATCH",
        "apigateway:POST",
        "apigateway:PUT"
      ],
      "Resource": [
        "arn:aws:apigateway:us-east-1::/apis/*/*"
      ]
    }
  ]
}
```

------

## 允許使用者僅建立或更新私有 REST API
<a name="security_iam_id-based-policy-examples-private-api"></a>

此範例政策使用條件索引鍵，要求使用者僅建立 `PRIVATE` API，並禁止可能會將 API 從 `PRIVATE` 變更為其他類型 (例如 `REGIONAL`) 的更新。

我們使用 `ForAllValues` 以要求每個新增至 API 中的 `EndpointType` 都是 `PRIVATE`。我們使用資源條件索引鍵來允許任何 API 更新，只要它是 `PRIVATE`。條件索引鍵存在時才會套用 `ForAllValues`。

我們使用非窮盡比對器 (`?`) 來明確比對 API ID，以防止允許授權者等非 API 資源。

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ScopePutToPrivateApis",
            "Effect": "Allow",
            "Action": [
                "apigateway:PUT"
            ],
            "Resource": [
                "arn:aws:apigateway:us-east-1::/restapis",
                "arn:aws:apigateway:us-east-1::/restapis/??????????"
            ],
            "Condition": {
                "ForAllValues:StringEquals": {
                    "apigateway:Resource/EndpointType": "PRIVATE"
                }
            }
        },
        {
            "Sid": "ScopeToPrivateApis",
            "Effect": "Allow",
            "Action": [
                "apigateway:DELETE",
                "apigateway:PATCH",
                "apigateway:POST"
            ],
            "Resource": [
                "arn:aws:apigateway:us-east-1::/restapis",
                "arn:aws:apigateway:us-east-1::/restapis/??????????"
            ],
            "Condition": {
                "ForAllValues:StringEquals": {
                    "apigateway:Request/EndpointType": "PRIVATE",
                    "apigateway:Resource/EndpointType": "PRIVATE"
                }
            }
        },
        {
            "Sid": "AllowResourcePolicyUpdates",
            "Effect": "Allow",
            "Action": [
                "apigateway:UpdateRestApiPolicy"
            ],
            "Resource": [
                "arn:aws:apigateway:us-east-1::/restapis/*"
            ]
        }
    ]
}
```

------

## 要求 API 路由具有授權
<a name="security_iam_id-based-policy-examples-require-authorization"></a>

如果路由沒有授權，此政策會導致嘗試建立或更新路由 (包括透過[匯入](https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis.html#ImportApi)) 失敗。如果金鑰不存在，例如沒有建立或更新路由時，則 `ForAnyValue` 會評估為 False。我們使用 `ForAnyValue`，因為可以透過匯入建立多個路由。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowUpdatesOnApisAndRoutes",
      "Effect": "Allow",
      "Action": [
        "apigateway:POST",
        "apigateway:PATCH",
        "apigateway:PUT"
      ],
      "Resource": [
        "arn:aws:apigateway:us-east-1::/apis",
        "arn:aws:apigateway:us-east-1::/apis/??????????",
        "arn:aws:apigateway:us-east-1::/apis/*/routes",
        "arn:aws:apigateway:us-east-1::/apis/*/routes/*"
      ]
    },
    {
      "Sid": "DenyUnauthorizedRoutes",
      "Effect": "Deny",
      "Action": [
        "apigateway:POST",
        "apigateway:PATCH",
        "apigateway:PUT"
      ],
      "Resource": [
        "arn:aws:apigateway:us-east-1::/apis",
        "arn:aws:apigateway:us-east-1::/apis/*"
      ],
      "Condition": {
        "ForAnyValue:StringEqualsIgnoreCase": {
          "apigateway:Request/RouteAuthorizationType": "NONE"
        }
      }
    }
  ]
}
```

------

## 防止使用者建立或更新 VPC 連結
<a name="security_iam_id-based-policy-examples-deny-vpc-link"></a>

此政策可防止使用者建立或更新 VPC 連結。VPC 連結可以公開 Amazon VPC 內的資源給 VPC 以外的用戶端。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DenyVPCLink",
      "Effect": "Deny",
      "Action": [
        "apigateway:POST",
        "apigateway:PUT",
        "apigateway:PATCH"
      ],
      "Resource": [
        "arn:aws:apigateway:{{us-east-1}}::/vpclinks",
        "arn:aws:apigateway:{{us-east-1}}::/vpclinks/*"
      ]
    }
  ]
}
```

------

## 使用路由規則的範例政策
<a name="security_iam_id-based-policy-examples-routing-mode"></a>

下列範例政策說明如何使用 RoutingRule 條件索引鍵，來控制使用者如何將流量從其自訂網域名稱路由至其 REST API。您可以使用這些範例，為使用者可制訂的路由規則建立更精細的政策。如需詳細資訊，請參閱[將 API 階段連線至 REST API 自訂網域名稱的路由規則](rest-api-routing-rules.md)。

### 防止使用者變更自訂網域名稱路由請求的方式
<a name="security_iam_id-based-policy-examples-routing-mode-1"></a>

此政策可防止使用者建立或更新 `BasePathMapping`、`ApiMapping` 或 `RoutingRule`。這些資源全都可能會變更自訂網域名稱將請求路由至 API 的方式。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DenyAccessBasePathMappingsApiMappingsRoutingRules",
      "Effect": "Deny",
      "Action": "apigateway:*",
      "Resource": [
        "arn:aws:apigateway:{{us-east-1}}::/domainnames/{{example.com}}/basepathmappings/*",
        "arn:aws:apigateway:{{us-east-1}}::/domainnames/{{example.com}}/apimappings/*",
        "arn:aws:apigateway:{{us-east-1}}:{{111122223333}}:/domainnames/{{example.com}}/routingrules/*"
      ]
    }
  ]
}
```

------

### 允許使用者更新特定優先順序的路由規則
<a name="security_iam_id-based-policy-examples-routing-mode-2"></a>

此政策只允許使用者將路由規則更新為 1001 到 2000 之間的優先順序。您可以使用此規則將生產規則與較低優先順序的規則分開，然後允許使用者修改較低優先順序的規則，而不會影響生產規則。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "UpdatingRoutingRulePriorityBetween1001And2000",
      "Effect": "Allow",
      "Action": "apigateway:UpdateRoutingRule",
      "Resource": "arn:aws:apigateway:us-east-1:111122223333:/domainnames/example.com/routingrules/*",
      "Condition": {
        "NumericGreaterThanEquals": {
          "apigateway:Resource/Priority": 1001,
          "apigateway:Request/Priority": 1001
        },
       "NumericLessThanEquals": {
          "apigateway:Resource/Priority": 2000,
          "apigateway:Request/Priority": 2000
        } 
      }
    }
  ]
}
```

------

### 允許使用者更新特定基本路徑值的路由規則或基本路徑映射
<a name="security_iam_id-based-policy-examples-routing-mode-3"></a>

此政策只允許使用者更新開頭為 `orders` 的任何基本路徑的基本路徑映射，或更新與開頭為 `orders` 的基本路徑相符的路由規則。在此政策中，使用者可以更新 `orders/create` 或 `orders123` 的基本路徑映射或路由規則，但不能更新 `payment/orders`。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
      {
        "Sid": "AllowUpdateRoutingRuleUnderPathOrders",
        "Effect": "Allow",
        "Action": "apigateway:UpdateRoutingRule",
        "Resource": "arn:aws:apigateway:us-east-1:111122223333:/domainnames/example.com/routingrules/*",
        "Condition": {
            "ForAllValues:StringLike": {
                "apigateway:Request/ConditionBasePaths": ["orders*"],
                "apigateway:Resource/ConditionBasePaths": ["orders*"]
            },
            "Null":{
                 "apigateway:Request/ConditionBasePaths":"false",
                 "apigateway:Resource/ConditionBasePaths":"false"             
          }
        }
      }
  ]
}
```

------

### 允許使用者將路由模式更新為特定值
<a name="security_iam_id-based-policy-examples-routing-mode-4"></a>

此政策只允許使用者將路由模式更新為 `API_MAPPING_ONLY` 和 `ROUTING_RULE_THEN_API_MAPPING`。如需路由模式的詳細資訊，請參閱 [為您的自訂網域名稱設定路由模式](set-routing-mode.md)。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
        {
           "Sid": "AllowUpdateRoutingModeToAnythingWithApiMapping",
           "Effect": "Allow",
           "Action": ["apigateway:PATCH"],
           "Resource": "arn:aws:apigateway:us-east-1::/domainnames/example.com",
              "Condition": {
               "StringLike": {
                   "apigateway:Request/RoutingMode":"*API_MAPPING*"
               }
           }
       }
    ]
}
```

------