

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

# 建立 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)，請確認資源政策中的所有帳戶都已啟用區域。