

# 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 Gateway의 프라이빗 REST API](apigateway-private-apis.md) 섹션을 참조하세요.

## API Gateway API에 리소스 정책 연결
<a name="apigateway-resource-policies-create-attach-procedure"></a>

다음 절차는 API Gateway API에 리소스 정책을 연결하는 방법을 보여줍니다.

------
#### [ AWS Management Console ]

**API Gateway API에 리소스 정책을 연결하려면**

1. [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)에서 API Gateway 콘솔에 로그인합니다.

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에서 {"Message":"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-east-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)에 있는 경우 리소스 정책의 모든 계정에 리전이 활성화되어 있는지 확인하세요.