6

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'
0bj3ct
  • 1,400
  • 4
  • 22
  • 51
  • 1
    Have you tried [this syntax?](https://github.com/awslabs/serverless-application-model/blob/master/examples/2016-10-31/api_gateway_responses/template.yaml) (With `Headers:` under `ResponseParameters`) – Mike Patrick May 21 '20 at 22:27
  • Awesome, it worked! Thank you @MikePatrick. Please put it in answers so I can accept. – 0bj3ct May 22 '20 at 21:55

1 Answers1

15

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: "'*'"
Mike Patrick
  • 10,699
  • 1
  • 32
  • 54
  • 1
    Can't thank you enough for this! I have been searching for this for hours!! The linked sample application code is also 404 now. I ended up there from release notes but hit a dead end because of 404 until I saw your response here with an example yml snippet. – lakshminb7 Nov 11 '20 at 08:16
  • I'm still receiving an error when this is configured: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. Is there a way to fix this? – rvwsd Jan 26 '22 at 19:11
  • On Angular I was receiving 0 as status code and with this it solved my issue. Cheers mate! – Simon Azzopardi Mar 18 '22 at 14:58