如何在CloudFormation模板中为API Gateway启用默认4XX/5XX的CORS
CloudFormation配置API Gateway全局4XX/5XX CORS头方案
仅为业务方法的200响应配置CORS头无法覆盖API Gateway层面直接返回的网关级错误(比如403 API Key缺失、401鉴权失败、500服务内部错误等),这类响应不会走自定义的方法响应配置,需要单独配置AWS::ApiGateway::GatewayResponse资源实现和控制台勾选DEFAULT 4XX/5XX完全等价的效果。
完整配置示例(YAML格式)
1. 4XX类网关响应CORS配置
ApiGatewayDefault4XXGatewayResponse: Type: AWS::ApiGateway::GatewayResponse Properties: RestApiId: !Ref YourRestApiResourceId # 替换为自身API Gateway的资源ID ResponseType: DEFAULT_4XX ResponseParameters: gatewayresponse.header.Access-Control-Allow-Origin: "'https://your-allowed-domain.com'" # 生产环境禁止使用通配符* gatewayresponse.header.Access-Control-Allow-Methods: "'OPTIONS,GET,POST,PUT,DELETE,PATCH'" gatewayresponse.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'" StatusCode: "400"
2. 5XX类网关响应CORS配置
ApiGatewayDefault5XXGatewayResponse: Type: AWS::ApiGateway::GatewayResponse Properties: RestApiId: !Ref YourRestApiResourceId # 替换为自身API Gateway的资源ID ResponseType: DEFAULT_5XX ResponseParameters: gatewayresponse.header.Access-Control-Allow-Origin: "'https://your-allowed-domain.com'" # 与4XX配置保持一致 gatewayresponse.header.Access-Control-Allow-Methods: "'OPTIONS,GET,POST,PUT,DELETE,PATCH'" gatewayresponse.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'" StatusCode: "500"
注意事项
ResponseParameters内的所有头值必须使用单引号包裹双引号的格式,这是CloudFormation向API Gateway传递字符串常量的固定写法,格式错误会导致配置失效- 原有OPTIONS预检请求的CORS配置不需要改动,本次配置仅补充网关级错误响应的跨域头
- 配置完成后需要触发一次API Gateway部署才会生效,如果使用
AWS::ApiGateway::Deployment资源,可给该资源添加DependsOn依赖指向上述两个GatewayResponse资源,实现配置更新后自动重新部署 - 若使用的是HTTP API而非REST API,不需要配置GatewayResponse资源,直接在CorsConfiguration中补充对应头配置即可
内容的提问来源于stack exchange,提问作者Ironman_255
相关产品推荐
相关产品推荐

