简体   繁体   中英

AWS cloudformation template.yml fails when I try to use method OPTIONS for CORS preflight (Lambda)

I tried to add a block for method OPTIONS to accept and forward to my lambda proxy also OPTIONS events. But cloudformation fails - but I can not find details why.

This is the block I tried:

    CorsPreflightEvent:
      Type: Api
      Properties:
        Path: /
        Method: options
        Auth:
          Authorizer: NONE

This is the full block:

  MyApp:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub 'awscodestar-${ProjectId}-lambda-01'
      Handler: index.handler
      Runtime: python3.9
      Timeout: 10
      Role:
        Fn::GetAtt:
        - LambdaExecutionRole
        - Arn
      Events:
        CorsPreflightEvent:
          Type: Api
          Properties:
            Path: /
            Method: options
            Auth:
              Authorizer: NONE
        GetEventAll:
          Type: Api
          Properties:
            Path: /
            Method: get
        GetEventSectionCat:
          Type: Api
          Properties:
            Path: /{subject}/{category}
            Method: get
        PostEvent:
          Type: Api
          Properties:
            Path: /
            Method: post

In general I want to allow OPTIONS without CORS. So I added to my python a OPTIONS response. I guess it should work. But it shall react on any path. Thats why I also tried this path before:

/{proxy+}

I want to disable CORS for any requests, but chrome complains, that is why I try to send this header in my Python - which should be done for all kind of requests:

headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
          }

Does anyone see what is wrong with my template.yml and why the step "GenerateChangeSet" may fail?


Meanwhile I switched to an easier solution to disable cors. Not by code but in template.yml I added this block:

Globals:
  Api:
    Cors:
      AllowMethods: "'OPTIONS,POST,GET'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"

This thread helped me to find the issue.

There is a tool mentioned: cfn-lint , which was able to give me a useful error message:

E0001 Error transforming template: Resource with id [MyApp] is invalid. Event with id [CorsPreflightEven t] is invalid. Unable to set Authorizer on API method [options] for path [/] because 'NONE' is only a valid value when a DefaultAuthorizer on the API is specified.

So I removed the Auth part. Now it goes through pipeline process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM