

# 使用 API Gateway 资源策略控制对 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 管理控制台、AWS CLI 或 AWS SDK，为 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 的权限的 Resource 格式](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 的权限的 Action 格式](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)。
+ **主体** – 允许访问语句中的操作和资源的账户或用户。在资源策略中，主体是接收此权限的用户或账户。

下面的资源策略示例展示了上述常用策略元素。该策略向其源 IP 地址位于地址块 *123.4.5.6/24* 内的任何用户授予对指定 *region* 中的指定 *account-id* 下的 API 的访问权限。如果用户的源 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_cn/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 端点调用，其 VPC 端点 ID 为 `vpce-1a2b3c4d`。在“预身份验证”评估期间，只有来自示例中所述的 VPC 端点的调用才允许向前推进并评估 Lambda 授权方。阻止所有剩余的调用。如果为私有 API 使用自定义域名，则此授权工作流程相同。

![\[资源策略和 Lambda 授权方的授权流程。\]](http://docs.aws.amazon.com/zh_cn/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 policy 和资源策略都明确允许调用方继续操作。有关更多信息，请参阅[表 B](#apigateway-resource-policies-iam-policies-interaction)。

然而，如果调用方和 API 所有者在同一 AWS 账户中，则 IAM 用户策略或资源策略必须明确允许调用方继续操作。有关更多信息，请参阅[表 A](#apigateway-resource-policies-iam-policies-interaction)。

![\[资源策略和 Lambda 身份验证的授权流程。\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/apigateway-auth-iam-resource-policy.png)


以下是跨账户资源策略的一个示例。假定 IAM policy 包含允许效果，此资源策略将仅允许来自 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_cn/apigateway/latest/developerguide/images/apigateway-auth-cognito-resource-policy.png)


下面是资源策略的一个示例，该策略只允许从指定的源 IP 调用（假定 Amazon Cognito 身份验证令牌包含允许）。有关更多信息，请参阅[表 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 资源策略** | **产生的行为** | 
| --- | --- | --- | 
| 允许 | 允许 | 允许 | 
| 允许 | 既不允许也不拒绝 | 允许 | 
| 允许 | 拒绝 | 显式拒绝 | 
| 既不允许也不拒绝 | 允许 | 允许 | 
| 既不允许也不拒绝 | 既不允许也不拒绝 | 隐式拒绝 | 
| 既不允许也不拒绝 | 拒绝 | 显式拒绝 | 
| 拒绝 | 允许 | 显式拒绝 | 
| 拒绝 | 既不允许也不拒绝 | 显式拒绝 | 
| 拒绝 | 拒绝 | 显式拒绝 | 

表 B 列出了对 API Gateway API 的访问由 IAM 策略（或 Amazon Cognito 用户池授权方）和 API Gateway 资源策略（两者位于不同 AWS 账户中）控制时产生的行为。如果其中一个静默（既不允许也不拒绝），则跨账户访问会被拒绝。这是因为跨账户访问要求资源策略和 IAM 策略（或 Amazon Cognito 用户池授权方）均明确授予访问权限。


| **IAM 策略（或 Amazon Cognito 用户池授权方）** | **API Gateway 资源策略** | **产生的行为** | 
| --- | --- | --- | 
| 允许 | 允许 | 允许 | 
| 允许 | 既不允许也不拒绝 | 隐式拒绝 | 
| 允许 | 拒绝 | 显式拒绝 | 
| 既不允许也不拒绝 | 允许 | 隐式拒绝 | 
| 既不允许也不拒绝 | 既不允许也不拒绝 | 隐式拒绝 | 
| 既不允许也不拒绝 | 拒绝 | 显式拒绝 | 
| 拒绝 | 允许 | 显式拒绝 | 
| 拒绝 | 既不允许也不拒绝 | 显式拒绝 | 
| 拒绝 | 拒绝 | 显式拒绝 | 

# 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>

以下示例资源策略通过[签名版本 4](https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html)（SigV4）或[签名版本 4a](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html#how-sigv4a-works)（SigV4a）协议，将一个 AWS 账户中的 API 访问权限授予位于另一个 AWS 账户中的两个角色。具体而言，向由 `account-id-2` 标识的 AWS 账户的开发人员和管理员角色授予了 `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。对于私有 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. 通过以下网址登录到 Amazon 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，则需要重新进行部署以使资源策略生效。

------
#### [ 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>

下表包含可针对每种授权类型，可在 API Gateway 中的 API 资源策略中使用的AWS条件键。

有关这些AWS条件键的更多信息，请参阅[AWS全局条件上下文键](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)。


| **条件键**： | **标准** | **是否需要 `AuthN`？** | **授权类型** | 
| --- | --- | --- | --- | 
| aws:CurrentTime | 无 | 否 | All | 
| aws:EpochTime | 无 | 否 | All | 
| 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 标头中提供了值时存在。 | 否 | All | 
| aws:SecureTransport | 无 | 否 | All | 
| aws:SourceArn | 无 | 否 | All | 
| aws:SourceIp | 无 | 否 | All | 
| aws:SourceVpc | 此键只能用于私有 API。 | 否 | All | 
| aws:SourceVpce | 此键只能用于私有 API。 | 否 | All | 
| aws:VpcSourceIp | 此键只能用于私有 API。 | 否 | All | 
| aws:UserAgent | 键仅在调用方在 HTTP 标头中提供了值时存在。 | 否 | All | 
| aws:userid | 无 | 是 | IAM | 
| aws:username | 无 | 是 | IAM | 