amazon-web-services - 通过 AWS SAM 模板禁用 API Gateway 中一种方法资源终端节点的安全性

标签 amazon-web-services swagger aws-cloudformation aws-api-gateway aws-serverless

我正在使用 AWS Serverless 创建由 Lambda 函数支持的 API 网关。

我定义了以下资源和方法:

/projects
   -> GET (should require API key)
   -> OPTIONS (should not, since it is used for CORS preflight)

我遇到了 CORS 问题并需要 API key 。由于 AWS 管理控制台中的 API Key required,前端客户端代码在启动预检 CORS OPTIONS 请求时收到 403 Forbidden 错误对于 OPTIONS 方法,设置为 True

我想专门针对 OPTIONS 请求禁用安全性,但保留所有其他方法(GETPOST 等)的安全性。这是我的资源定义(您可以看到我在我的 Auth 对象中设置了默认的 ApiKeyRequired: true:

  MyApi:
    Type: 'AWS::Serverless::Api'
    Name: MyApi
    Properties:
      Auth:
        AddDefaultAuthorizerToCorsPreflight: true
        ApiKeyRequired: true # sets for all methods
      Cors:
        AllowCredentials: true
        AllowHeaders: '"Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token"'
        AllowMethods: '"POST,GET,OPTION"'
        AllowOrigin: '"*"'
        MaxAge: '"600"'
      StageName: !Ref StageName
      DefinitionBody:
        swagger: 2.0
        info:
          title: !Sub API-Lambda-${StageName}
          description: "API for MyApi"
          version: "1.0.0"
        paths:
          /projects:
            get:
              produces:
                - application/json
              responses:
                "200":
                  description: OK
              x-amazon-apigateway-any-method:
                produces:
                  - application/json
              x-amazon-apigateway-integration:
                httpMethod: post
                type: aws_proxy
                uri:
                  Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetAllProjectsFunction.Arn}/invocations
            options:
              consumes:
                - application/json
              produces:
                - application/json
              responses:
                '200':
                  description: 200 response
                  headers:
                    Access-Control-Allow-Origin:
                      type: string
                    Access-Control-Allow-Methods:
                      type: string
                    Access-Control-Allow-Headers:
                      type: string
              x-amazon-apigateway-integration:
                responses:
                  default:
                    statusCode: 200
                    responseParameters:
                      method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
                      method.response.header.Access-Control-Allow-Headers: "'Content-Type,mode,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
                      method.response.header.Access-Control-Allow-Origin: "'*'"
                passthroughBehavior: when_no_match
                requestTemplates:
                  application/json: "{\"statusCode\": 200}"
                type: mock
          /projects/{userId}:
            get:
              responses:
                "200":
                  description: OK
              x-amazon-apigateway-any-method:
                produces:
                  - application/json
              x-amazon-apigateway-integration:
                httpMethod: post
                type: aws_proxy
                uri:
                  Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetProjectsForUserFunction.Arn}/invocations
            options:
              consumes:
                - application/json
              responses:
                '200':
                  description: 200 response
                  headers:
                    Access-Control-Allow-Origin:
                      type: string
                    Access-Control-Allow-Methods:
                      type: string
                    Access-Control-Allow-Headers:
                      type: string
              x-amazon-apigateway-integration:
                responses:
                  default:
                    statusCode: 200
                    responseParameters:
                      method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
                      method.response.header.Access-Control-Allow-Headers: "'Content-Type,mode,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
                      method.response.header.Access-Control-Allow-Origin: "'*'"
                passthroughBehavior: when_no_match
                requestTemplates:
                  application/json: "{\"statusCode\": 200}"
                type: mock

我知道 Swagger documentation说我可以通过为每个资源方法添加一个 security 对象来覆盖安全性。这个SO post还建议我可以通过将 security 对象设置为空列表来禁用安全性。

但是,我尝试了以下方法:

        options:
          consumes:
            - application/json
          produces:
            - application/json
          security:
            -
          responses: ...

并且还简单地将 security 设为 None 对象:

        options:
          consumes:
            - application/json
          produces:
            - application/json
          security:
          responses: ...

在这两种情况下,我在尝试使用 aws sam deploy 进行部署时都会收到以下错误:

Waiting for changeset to be created.. Error: Failed to create changeset for the stack: my-app, ex: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Transform AWS::Serverless-2016-10-31 failed with: Internal transform failure.

这似乎是我的安全定义是错误的。如何禁用资源的一种方法(即 OPTIONS 方法)的安全性?

更新:

我使用以下语法获取了要部署的模板:

    options:
      consumes:
        - application/json
      produces:
        - application/json
      security:
        - {}
      responses:

但是,即使在部署之后,我的控制台中仍然有这个:

enter image description here

老实说,我现在很茫然,因为使用常规的 AWS::ApiGateway::Method 资源很容易做到这一点(只需将 ApiKeyRequired 设置为 true )。

最佳答案

您只需设置 AddDefaultAuthorizerToCorsPreflight: false 即可按照您的意愿导致 OPTIONS 请求不安全。

请参阅文档的这一部分:

If the DefaultAuthorizer and Cors properties are set, then setting AddDefaultAuthorizerToCorsPreflight will cause the default authorizer to be added to the Options property in the OpenAPI section.

引用号:https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-api-apiauth.html

关于amazon-web-services - 通过 AWS SAM 模板禁用 API Gateway 中一种方法资源终端节点的安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649177/

相关文章:

amazon-web-services - 如何 Fn::Split 追加现有数组?

c# - 在 Azure 或 Amazon 上托管控制台应用程序,可能吗?

amazon-web-services - AWS Beanstalk - 无法使用配置文件运行命令

swagger - 在 Swagger UI 中实现搜索

java - Spring Boot Controller 端点未启用?

amazon-web-services - 如何设置云编码模板的访问权限?

amazon-web-services - AWS Ubuntu 18.04 AMI 软件包安装失败

javascript - 为什么我不能在我的亚马逊服务器上使用新的 XMLHttpRequest?

symfony - Nelmio ApiDoc 3.0 - 从 SwaggerUI 中排除部分

amazon-web-services - AWS ELB : Failed to load resource: the server responded with a status of 503 (Service Unavailable: Back-end server is at capacity)