为 API 网关 lambda 授权方设置 CORS 标头时出错



我有一个 lambda 授权方用于我的 API 网关授权。当授权方返回 401 或 403 时,我没有在响应标头中返回 CORS。我正在使用AWS::Serverless::Api资源,经过一些研究,我在这里发现我需要设置GatewayResponses以返回 4XX 响应的自定义标头。

我的 API 网关定义如下所示:

resApiGateway:
Type: AWS::Serverless::Api
Properties:
StageName: !Sub "${env}"
EndpointConfiguration: !If [IsLocal, "REGIONAL", "EDGE"]
Cors:
AllowMethods: "'OPTIONS,GET,POST,PUT,DELETE'"
AllowHeaders: "'Content-Type,X-Amz-Date,Authorization'"
AllowOrigin: "'*'"
GatewayResponses:
DEFAULT_4XX:
ResponseParameters:
"gatewayresponse.header.Access-Control-Allow-Origin": "'*'"
...
...

但是我在 cfn 堆栈部署时遇到错误:

Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [resApiGateway] is invalid. Invalid gateway response parameter 'gatewayresponse.header.Access-Control-Allow-Origin'

此功能随 SAM v1.11.0 一起发布。 发行说明包含指向此示例应用程序模板的链接,该模板演示了该功能。

不幸的是,亚马逊自己的SAM文档(您链接到该文档(仅将您指向其OpenAPI扩展文档。

这些文档似乎显示了如何将 API 网关配置为将此功能与 OpenAPI 规范一起使用,而不是与 SAM 模板一起使用。


若要在 SAM 模板中指定GatewayResponses,请使用示例应用程序中找到的语法:

Resources:
restApiGateway:
Type: AWS::Serverless::Api
Properties:
GatewayResponses:
DEFAULT_4XX:
ResponseParameters:
Headers:
Access-Control-Allow-Origin: "'*'"

最新更新