使用AWS CDK为AWS API网关启用CORS

时间:2018-10-11 04:25:49

标签: amazon-cloudformation aws-api-gateway aws-cdk

我正在尝试使用AWS CDK构建应用程序,如果要使用AWS Console手动构建应用程序,通常我会在API网关中启用CORS。

即使我可以从API网关中导出大张旗鼓,并且已经找到了许多选项来为OPTIONS方法生成Mock端点,但我看不出如何使用CDK来做到这一点。目前,我正在尝试:

const apigw             = require('@aws-cdk/aws-apigateway');

其中:

var api                 = new apigw.RestApi(this, 'testApi');

并定义OPTIONS方法,例如:

const testResource   = api.root.addResource('testresource');

var mock = new apigw.MockIntegration({
                    type: "Mock",
                    methodResponses: [
                            {
                                    statusCode: "200",
                                    responseParameters : {
                                            "Access-Control-Allow-Headers" : "string",
                                            "Access-Control-Allow-Methods" : "string",
                                            "Access-Control-Allow-Origin" : "string"
                                    }
                            }
                    ],
                    integrationResponses: [
                            {
                                    statusCode: "200",
                                    responseParameters: {
                                            "Access-Control-Allow-Headers" :  "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'",
                                            "Access-Control-Allow-Origin" : "'*'",
                                            "Access-Control-Allow-Methods" : "'GET,POST,OPTIONS'"
                                    }
                            }
                    ],
                    requestTemplates: {
                            "application/json": "{\"statusCode\": 200}"
                    }
            });

            testResource.addMethod('OPTIONS', mock);

但这不会部署。当我运行“ cdk deploy”时,我从cloudformation堆栈中获得的错误消息是:

Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression specified: Access-Control-Allow-Origin] (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException;

想法?

4 个答案:

答案 0 :(得分:8)

recent change使启用CORS变得更加简单:

const restApi = new apigw.RestApi(this, `api`, {
  defaultCorsPreflightOptions: {
    allowOrigins: apigw.Cors.ALL_ORIGINS
  }
});

答案 1 :(得分:1)

我自己还没有测试过,但是基于this answer,在定义MOCK集成时似乎需要使用一组稍有不同的键:

const api = new apigw.RestApi(this, 'api');

const method = api.root.addMethod('OPTIONS', new apigw.MockIntegration({
  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": "'GET,POST,OPTIONS'",
        "method.response.header.Access-Control-Allow-Origin": "'*'"
      },
      responseTemplates: {
        "application/json": ""
      }
    }
  ],
  passthroughBehavior: apigw.PassthroughBehavior.Never,
  requestTemplates: {
    "application/json": "{\"statusCode\": 200}"
  },
}));

// since "methodResponses" is not supported by apigw.Method (https://github.com/awslabs/aws-cdk/issues/905)
// we will need to use an escape hatch to override the property

const methodResource = method.findChild('Resource') as apigw.cloudformation.MethodResource;
methodResource.propertyOverrides.methodResponses = [
  {
    statusCode: '200',
    responseModels: {
      'application/json': 'Empty'
    },
    responseParameters: {
      'method.response.header.Access-Control-Allow-Headers': true,
      'method.response.header.Access-Control-Allow-Methods': true,
      'method.response.header.Access-Control-Allow-Origin': true
    }
  }
]

使用更多friendly API启用CORS将会很有用。

答案 2 :(得分:1)

随着CDK的最新更新,不再需要使用逃生舱口。

This version, originally created by Heitor Vital on github uses only native constructs.

export function addCorsOptions(apiResource: apigateway.IResource) {
    apiResource.addMethod('OPTIONS', new apigateway.MockIntegration({
        integrationResponses: [{
        statusCode: '200',
        responseParameters: {
            'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'",
            'method.response.header.Access-Control-Allow-Origin': "'*'",
            'method.response.header.Access-Control-Allow-Credentials': "'false'",
            'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE'",
        },
        }],
        passthroughBehavior: apigateway.PassthroughBehavior.NEVER,
        requestTemplates: {
        "application/json": "{\"statusCode\": 200}"
        },
    }), {
        methodResponses: [{
        statusCode: '200',
        responseParameters: {
            'method.response.header.Access-Control-Allow-Headers': true,
            'method.response.header.Access-Control-Allow-Methods': true,
            'method.response.header.Access-Control-Allow-Credentials': true,
            'method.response.header.Access-Control-Allow-Origin': true,
        },  
        }]
    })
}

我还使用其版本作为指南将相同的代码移植到python。

def add_cors_options(api_resource):
    """Add response to OPTIONS to enable CORS on an API resource."""
    mock = apigateway.MockIntegration(
        integration_responses=[{
            'statusCode': '200',
            'responseParameters': {
                'method.response.header.Access-Control-Allow-Headers':
                    "'Content-Type,\
                      X-Amz-Date,\
                      Authorization,\
                      X-Api-Key,\
                      X-Amz-Security-Token,X-Amz-User-Agent'",
                'method.response.header.Access-Control-Allow-Origin': "'*'",
                'method.response.header.Access-Control-Allow-Credentials':
                    "'false'",
                'method.response.header.Access-Control-Allow-Methods':
                    "'OPTIONS,\
                      GET,\
                      PUT,\
                      POST,\
                      DELETE'",
            }
        }],
        passthrough_behavior=apigateway.PassthroughBehavior.NEVER,
        request_templates={
            "application/json": "{\"statusCode\": 200}"
        }
    )
    method_response = apigateway.MethodResponse(
        status_code='200',
        response_parameters={
            'method.response.header.Access-Control-Allow-Headers': True,
            'method.response.header.Access-Control-Allow-Methods': True,
            'method.response.header.Access-Control-Allow-Credentials': True,
            'method.response.header.Access-Control-Allow-Origin': True
        }
    )
    api_resource.add_method(
        'OPTIONS',
        integration=mock,
        method_responses=[method_response]
    )

答案 3 :(得分:0)

背景

在尝试在Terraform中实现aws_api_gateway_integration_response时遇到了这个答案,偶然遇到了解决方案。

问题

我收到此错误消息:

Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression specified: POST,GET,OPTIONS]

aws_api_gateway_integration_response资源中,我有response_parameter键,如下所示:

response_parameters = {
    "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-Origin" = "*"
    "method.response.header.Access-Control-Allow-Methods" = "POST,GET,OPTIONS"
    # "method.response.header.Access-Control-Allow-Credentials" = "false"
  }

我认为一切都很好,因为我假设双引号是Terraform所需的全部。但是,事实并非如此。

解决方案

我必须在双引号内的值周围添加一个单引号。像这样:

response_parameters = {
    "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-Origin" = "'*'"
    "method.response.header.Access-Control-Allow-Methods" = "'POST,GET,OPTIONS'"
    # "method.response.header.Access-Control-Allow-Credentials" = "false"
  }