为 API 网关 lambda 授权方设置 CORS header 时出错
Error on setting CORS header for API Gateway lambda authorizer
我的 API 网关授权有一个 lambda 授权方。当授权方 returns 401 或 403 时,我没有得到 CORS 作为响应 header。我正在使用 AWS::Serverless::Api
资源,经过一些研究发现 here 我需要将 GatewayResponses
设置为 return 自定义 headers 以进行 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 一起发布。 release notes have a link to this sample application template,它演示了该功能。
不幸的是,Amazon 自己的 SAM 文档(您已链接到该文档)仅将您指向他们的 OpenAPI extension docs。
这些文档似乎展示了如何配置 API 网关以将此功能与 OpenAPI 规范一起使用,而不是与 SAM 模板一起使用。
要在 SAM 模板中指定 GatewayResponses
,请使用示例应用程序中的语法:
Resources:
restApiGateway:
Type: AWS::Serverless::Api
Properties:
GatewayResponses:
DEFAULT_4XX:
ResponseParameters:
Headers:
Access-Control-Allow-Origin: "'*'"
我的 API 网关授权有一个 lambda 授权方。当授权方 returns 401 或 403 时,我没有得到 CORS 作为响应 header。我正在使用 AWS::Serverless::Api
资源,经过一些研究发现 here 我需要将 GatewayResponses
设置为 return 自定义 headers 以进行 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 一起发布。 release notes have a link to this sample application template,它演示了该功能。
不幸的是,Amazon 自己的 SAM 文档(您已链接到该文档)仅将您指向他们的 OpenAPI extension docs。
这些文档似乎展示了如何配置 API 网关以将此功能与 OpenAPI 规范一起使用,而不是与 SAM 模板一起使用。
要在 SAM 模板中指定 GatewayResponses
,请使用示例应用程序中的语法:
Resources:
restApiGateway:
Type: AWS::Serverless::Api
Properties:
GatewayResponses:
DEFAULT_4XX:
ResponseParameters:
Headers:
Access-Control-Allow-Origin: "'*'"