

# 创建 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。

------
#### [ Amazon Web Services 管理控制台 ]

**将资源策略附加到 API Gateway API**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.amazonaws.cn/apigateway)。

1. 选择一个 REST API。

1. 在主导航窗格中，选择**资源策略**。

1. 选择**创建策略**。

1. （可选）选择**选择模板**以生成示例策略。

   在策略示例中，占位符括在双大括号 (`"{{placeholder}}"`) 内。将每个占位符（包括大括号）替换为必要的信息。

1. 如果您没有使用任何一个模板示例，则输入您的资源策略。

1. 选择**保存更改**。

如果先前已在 API Gateway 控制台中部署了 API，则需要重新进行部署以使资源策略生效。

------
#### [ Amazon CLI ]

要使用 Amazon CLI 创建新的 API 并向其附加资源策略，请使用以下 [create-rest-api](https://docs.amazonaws.cn/cli/latest/reference/apigateway/create-rest-api.html) 命令：

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

要使用 Amazon CLI 将资源策略附加到现有 API，请使用以下 [update-rest-api](https://docs.amazonaws.cn/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.amazonaws.cn/cli/latest/reference/apigateway/create-rest-api.html) 命令中。使用以下 [create-rest-api](https://docs.amazonaws.cn/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)。

------
#### [ Amazon CloudFormation ]

您可以使用 Amazon 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>

在资源策略中，如果您将主体设置为 Amazon 主体，如下所示：

------
#### [ 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.amazonaws.cn/glossary/latest/reference/glos-chap.html?icmpid=docs_homepage_addtlrcs#optinregion)，请确认资源政策中的所有账户都启用了该区域。