Search code examples
corsaws-cloudformationaws-api-gatewayaws-serverlesssam

SAM app deploy gives preflight error but if I create OPTIONS method in aws apigateway console my preflight passes


I'm using SAM to create an API in cloudformation.

QUESTION: Where in my SAM application template do I add the 'X-Requested-With' header? How can I edit my code so that the preflight will succeed without me having to go into the AWS console?

PROBLEM: I'm working with my preflight request and when I deploy my SAM application I get 403 FORBIDDEN in postman and when I go to the AWS console the header 'X-Requested-With' is not present.

If I try to just add the 'X-Requested-With' header afterward in the console it still gives the error, BUT if I delete the OPTIONS method in the console and create the OPTIONS method from scratch according to (https://enable-cors.org/server_awsapigateway.html) it works and I get a 200 OK in postman. enter image description here

enter image description here

CODE:

template.yaml

Globals:
  Function:
    Timeout: 10
  Api:
    Cors:
      AllowMethods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
      AllowHeaders: "'Content-Type,X-Amz-Date,X-Amz-Security-Token,Authorization,X-Api-Key,X-Requested-With,Accept,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Access-Control-Allow-Headers'"
      AllowOrigin: "'*'"

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        ApiKeyRequired: true

 MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: mypath/
      Handler: app.lambdaHandler
      Runtime: nodejs12.x
      Events:
        KrySeisoen:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /mypath
            Method: get
      Policies:
        - ...
      VpcConfig:
        SecurityGroupIds:
          - ...
        SubnetIds:
          - ...

Solution

  • So I was barking up the wrong tree.

    The problem that I was having was not with the 'X-Requested-With' header, but rather the fact that my SAM application was setting the ApiKeyRequired to true for all the methods.

    All I had to do was to set the ApiKeyRequired to false for all the options methods.

    Here is a link to another question with the solution to my problem. Preflight response 403 forbidden. How can I allow options method without x-api-key?