![](/img/trans.png)
[英]AWS API Gateway: User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:
[英]Is there no setting for AWS API Gateway REST API to disable execute-api endpoint in CloudFormation template?
我已經使用 CloudFormation 模板設置了 API 網關(v1,不是 v2) REST API 資源。 最近我注意到還創建了默認的 execute-api 端點,我可以在設置中將其禁用。
這個 API 的類型是
AWS::ApiGateway::RestApi
。
當然,我希望通過模板完成此操作,所以問題是:是否可以在 CloudFormation 模板中定義此設置,而不是必須在 AWS 控制台中手動單擊? 此選項可用於 CloudFormation 模板中的 APIGateway V2 API 資源 ( AWS::ApiGatewayV2::Api
) 但不適用於 APIGateway V1 REST API 資源 ( AWS::ApiGateway::RestApi
),即使它可以手動更改APIGateway V1 REST API 在控制台中。
對於AWS::ApiGateway::RestApi
,還有一種CLI 方法可以執行此操作。
以下是我用來搜索此設置的一些鏈接:
AWS::ApiGatewayV2::API
AWS::ApiGateway::RestApi
通過 CLI 禁用默認的 api-execute 端點
AWS::ApiGateway::RestApi cloudformation: DisableExecuteApiEndpoint最近添加了對禁用默認執行 API 端點的支持
MyRestApi:
Type: 'AWS::ApiGateway::RestApi'
Properties:
DisableExecuteApiEndpoint: true
您可以通過一個簡單的自定義資源禁用它。 下面是一個這樣的完整工作模板的例子:
Resources:
MyRestApi:
Type: 'AWS::ApiGateway::RestApi'
Properties:
Description: A test API
Name: MyRestAPI
LambdaBasicExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonAPIGatewayAdministrator
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
MyCustomResource:
Type: Custom::DisableDefaultApiEndpoint
Properties:
ServiceToken: !GetAtt 'MyCustomFunction.Arn'
APIId: !Ref 'MyRestApi'
MyCustomFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Description: "Disable default API endpoint"
Timeout: 30
Role: !GetAtt 'LambdaBasicExecutionRole.Arn'
Runtime: python3.7
Code:
ZipFile: |
import json
import logging
import cfnresponse
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
client = boto3.client('apigateway')
def lambda_handler(event, context):
logger.info('got event {}'.format(event))
try:
responseData = {}
if event['RequestType'] in ["Create"]:
APIId = event['ResourceProperties']['APIId']
response = client.update_rest_api(
restApiId=APIId,
patchOperations=[
{
'op': 'replace',
'path': '/disableExecuteApiEndpoint',
'value': 'True'
}
]
)
logger.info(str(response))
cfnresponse.send(event, context,
cfnresponse.SUCCESS, responseData)
else:
logger.info('Unexpected RequestType!')
cfnresponse.send(event, context,
cfnresponse.SUCCESS, responseData)
except Exception as err:
logger.error(err)
responseData = {"Data": str(err)}
cfnresponse.send(event,context,
cfnresponse.FAILED,responseData)
return
如果有人偶然發現這個使用 CDK 的答案,可以使用 AwsCustomResource 構造簡潔地完成此操作(無需定義 Lambda 函數):
const restApi = new apigw.RestApi(...);
const executeApiResource = new cr.AwsCustomResource(this, "execute-api-resource", {
functionName: "disable-execute-api-endpoint",
onCreate: {
service: "APIGateway",
action: "updateRestApi",
parameters: {
restApiId: restApi.restApiId,
patchOperations: [{
op: "replace",
path: "/disableExecuteApiEndpoint",
value: "True"
}]
},
physicalResourceId: cr.PhysicalResourceId.of("execute-api-resource")
},
policy: cr.AwsCustomResourcePolicy.fromStatements([new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["apigateway:PATCH"],
resources: ["arn:aws:apigateway:*::/*"],
})])
});
executeApiResource.node.addDependency(restApi);
您可以在 AWS CDK 中禁用它。 這是通過查找 CloudFormation 資源並將其設置為 true 來完成的。
const api = new apigateway.RestApi(this, 'api', );
(api.node.children[0] as apigateway.CfnRestApi).addPropertyOverride('DisableExecuteApiEndpoint','true')
這是 snorberhuis 提供的答案的 Python 變體。
rest_api = apigateway.RestApi(self,...)
cfn_apigw = rest_api.node.default_child
cfn_apigw.add_property_override('DisableExecuteApiEndpoint', True)
Amazon 關於“Abstractions and Escape Hatches”的文檔非常有助於理解這里發生的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.