

# Amazon API Gateway 基于身份的策略示例
<a name="security_iam_id-based-policy-examples"></a>

默认情况下，IAM 用户和角色无权创建或修改 API Gateway 资源。它们还无法使用Amazon Web Services 管理控制台、Amazon CLI 或者Amazon开发工具包执行任务。IAM 管理员必须创建 IAM 策略，以便为用户和角色授予权限以对所需的指定资源执行特定的 API 操作。然后，管理员必须将这些策略附加到需要这些权限的 IAM 用户或组。

有关如何创建 IAM 策略的信息，请参阅 *IAM 用户指南*中的[在 JSON 选项卡上创建策略](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-json-editor)。有关 API Gateway 特定的操作、资源和条件的信息，请参阅 [Amazon API Gateway Management 的操作、资源和条件键](https://docs.amazonaws.cn/service-authorization/latest/reference/list_amazonapigatewaymanagement.html)和 [Amazon API Gateway Management V2 的操作、资源和条件键](https://docs.amazonaws.cn/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 资源。这些操作可能会使 Amazon Web Services 账户产生成本。创建或编辑基于身份的策略时，请遵循以下指南和建议：
+ **Amazon 托管式策略及转向最低权限许可入门**：要开始向用户和工作负载授予权限，请使用 *Amazon 托管式策略*来为许多常见使用场景授予权限。您可以在 Amazon Web Services 账户 中找到这些策略。建议通过定义特定于您的使用场景的 Amazon 客户托管式策略来进一步减少权限。有关更多信息，请参阅《IAM 用户指南》**中的 [Amazon 托管策略](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies)或[工作职能的 Amazon 托管策略](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_job-functions.html)。
+ **应用最低权限**：在使用 IAM 策略设置权限时，请仅授予执行任务所需的权限。为此，您可以定义在特定条件下可以对特定资源执行的操作，也称为*最低权限许可*。有关使用 IAM 应用权限的更多信息，请参阅《IAM 用户指南》**中的 [IAM 中的策略和权限](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies.html)。
+ **使用 IAM 策略中的条件进一步限制访问权限**：您可以向策略添加条件来限制对操作和资源的访问。例如，您可以编写策略条件来指定必须使用 SSL 发送所有请求。如果通过特定 Amazon Web Services 服务（例如 Amazon CloudFormation）使用服务操作，您还可以使用条件来授予对服务操作的访问权限。有关更多信息，请参阅《IAM 用户指南》**中的 [IAM JSON 策略元素：条件](https://docs.amazonaws.cn/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.amazonaws.cn/IAM/latest/UserGuide/access-analyzer-policy-validation.html)。
+ **需要多重身份验证（MFA）**：如果您所处的场景要求您的 Amazon Web Services 账户 中有 IAM 用户或根用户，请启用 MFA 来提高安全性。若要在调用 API 操作时需要 MFA，请将 MFA 条件添加到您的策略中。有关更多信息，请参阅《IAM 用户指南》**中的[使用 MFA 保护 API 访问](https://docs.amazonaws.cn/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)。

有关 IAM 中的最佳实操的更多信息，请参阅《IAM 用户指南》**中的 [IAM 中的安全最佳实践](https://docs.amazonaws.cn/IAM/latest/UserGuide/best-practices.html)。

## 允许用户查看他们自己的权限
<a name="security_iam_id-based-policy-examples-view-own-permissions"></a>

该示例说明了您如何创建策略，以允许 IAM 用户查看附加到其用户身份的内联和托管式策略。此策略包括在控制台上完成此操作或者以编程方式使用 Amazon CLI 或 Amazon 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 的Amazon区域中获取有关标识符为 `a123456789` 的 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.amazonaws.cn/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>

 此示例策略允许用户在 `DisableExecuteApiEndpoint` 为 `true` 的前提下创建、更新或导入 API。当 `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.amazonaws.cn/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 链接，您可以向 VPC 之外的客户端公开 Amazon 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*"
               }
           }
       }
    ]
}
```

------