0

I would like to handle CORS OPTIONS requests using a lambda so that I can allow more than one origin. Here's the starting point for my APIGateway SAM declaration:

  TESTAPI:
    Type: AWS::Serverless::Api
    Properties:
      Name: TEST_API
      Cors:
        AllowOrigin: "'https://example.com'"  # only one origin allowed
        AllowCredentials: true
        AllowMethods: "'*'"
        AllowHeaders: "'*'"
      Auth:
        Authorizers:
          MyAuthorizer:
            UserPoolArn: arn:aws:cognito-idp:... # my user pool

To keep things simple, each lambda is declared to handle ANY request, like this:

  TESTEndpoint:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: TEST_endpoint
      Handler: package/module.handler_any
      Events:
        HttpAny:
          Type: Api
          Properties:
            Path: '/path/endpoint'
            Method: ANY
            RestApiId: !Ref TESTAPI
            Auth:
              Authorizer: MyAuthorizer

When I request OPTIONS from an endpoint using curl the handling lambda is invoked.

However, when I actually make a cross origin request the CORS headers declared above are used in the OPTIONS response, instead of the ones returned by my lambda. Likewise, if I don't declare CORS headers, then no CORS headers are returned in the OPTIONS response and so the request fails.

QUESTION: How can I prevent APIGateway from overriding my CORS headers?


UPDATE 2021-7-27

This question is about the OPTIONS method only. For all other methods (e.g. GET) the headers are included as defined by the Lambda and so CORS is allowed for more than one origin.

AngelGabriel
  • 694
  • 4
  • 12
  • Does this answer your question? [How to Enable CORS for an AWS API Gateway Resource](https://stackoverflow.com/questions/48539161/how-to-enable-cors-for-an-aws-api-gateway-resource) – petey Jul 27 '21 at 14:00
  • See above link on how to edit your function to override with headers you are interested in overriding – petey Jul 27 '21 at 14:02
  • That question seems to be concerned with the GET method - the solution is to include the required headers. I have already done this, and it works for methods other than OPTIONS. – AngelGabriel Jul 27 '21 at 23:30

0 Answers0