在 Cloudformation 模板中为 API 网关启用 CORS [英] Enable CORS for API Gateway in Cloudformation template

查看:29
本文介绍了在 Cloudformation 模板中为 API 网关启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的环境创建 AWS Cloudformation 模板,但找不到为 API 网关方法启用 CORS 的方法.

I'm creating AWS Cloudformation template for my environment and I can't find a way to enable CORS for API Gateway method.

我可以使用 AWS 控制台配置它(这里是官方文档),但我如何在 Cloudformation 模板中做到这一点?

I can configure it using AWS console (here is the official doc), but how can I do it in the Cloudformation template?

推荐答案

经过反复试验,我发现与 CORS 控制台向导相比,以下 CloudFormation 模板片段将生成等效的 OPTIONS 方法:

After some trial and error, I found that the following CloudFormation template snippet will produce an equivalent OPTIONS method when compared to the CORS console wizard:

OptionsMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    AuthorizationType: NONE
    RestApiId:
      Ref: MyApi
    ResourceId:
      Ref: MyResourceOnWhichToEnableCORS
    HttpMethod: OPTIONS
    Integration:
      IntegrationResponses:
      - StatusCode: 200
        ResponseParameters:
          method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
          method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
          method.response.header.Access-Control-Allow-Origin: "'*'"
        ResponseTemplates:
          application/json: ''
      PassthroughBehavior: WHEN_NO_MATCH
      RequestTemplates:
        application/json: '{"statusCode": 200}'
      Type: MOCK
    MethodResponses:
    - StatusCode: 200
      ResponseModels:
        application/json: 'Empty'
      ResponseParameters:
          method.response.header.Access-Control-Allow-Headers: false
          method.response.header.Access-Control-Allow-Methods: false
          method.response.header.Access-Control-Allow-Origin: false

*注 1:这是一个采用默认值的 POST 示例.显然,您需要更新 Access-Control-Allow-Methods 以包含您需要的值.

*Note 1: This is an example of taking the defaults for a POST. Obviously, you'll need to update Access-Control-Allow-Methods to include the values you need.

*注 2:感谢 AWS CloudFormation 团队最近引入了 YAML 支持.如果您需要转换为/从 YAML/JSON,我发现这个站点很方便:http://www.json2yaml.com/

*Note 2: Kudos to the AWS CloudFormation team for recently introducing YAML support. If you need to convert to/from YAML/JSON, I have found this site handy: http://www.json2yaml.com/

这篇关于在 Cloudformation 模板中为 API 网关启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆