I have a lambda authorizer for my API Gateway authorization. When authorizer returns 401 or 403 I do not get CORS back in response header. I am using AWS::Serverless::Api
resource, and after some research found here that I need to set GatewayResponses
to return custom headers for 4XX responses.
My Api Gateway definition looks like:
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": "'*'"
...
...
But I am getting error on cfn stack deployment:
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'
This feature was released with SAM v1.11.0. The release notes have a link to this sample application template, which demonstrates the feature.
Unfortunately, Amazon's own SAM documentation (which you linked to) only points you toward their OpenAPI extension docs.
These docs seem to show how you would configure API Gateway to use this feature with an OpenAPI specification, rather than with a SAM template.
To specify GatewayResponses
in your SAM template, use the syntax found in the sample application:
Resources:
restApiGateway:
Type: AWS::Serverless::Api
Properties:
GatewayResponses:
DEFAULT_4XX:
ResponseParameters:
Headers:
Access-Control-Allow-Origin: "'*'"