Search code examples
corsaws-api-gatewayaws-cdkaws-http-api

cdk http api cors configuration not working


I have this code which creates an http api, but the cors configuration is not working even though it shows up correctly in the console after deployment. I can still send a request from postman and execute the lambda behind the api, which shouldn't happen considering this cors configuration.

const someApiDomain = new apigateway.DomainName(this, 'mydomain', {
  domainName: 'api.example.com',
  endpointType: apigateway.EndpointType.REGIONAL,
  certificate: someCert
})

const httpApi = new apigateway.HttpApi(this, 'my-api', {
  apiName: `my-api`,
  createDefaultStage: true,
  disableExecuteApiEndpoint: true,
  defaultDomainMapping: {
    domainName: someApiDomain
  },
  corsPreflight: {
    allowHeaders: [
      'Content-Type',
      'X-Amz-Date'
    ],
    allowMethods: [
      apigateway.CorsHttpMethod.OPTIONS,
      apigateway.CorsHttpMethod.POST,
    ],
    allowCredentials: false,
    allowOrigins: ['https://example.com']
  },
});

httpApi.addRoutes({
  methods: [apigateway.HttpMethod.POST],
  path: '/myapi',
  integration: new apigatewayintegrations.LambdaProxyIntegration({
    handler: myFunction,
  }),
});

new route53.ARecord(this, 'myapirecord', {
  zone: someHostedZone,
  recordName: 'api.example.com',
  target: route53.RecordTarget.fromAlias(
    new route53targets.ApiGatewayv2DomainProperties(someApiDomain.regionalDomainName, someApiDomain.regionalHostedZoneId)
  ),
});

Is the route53 record bypassing something here?


Solution

  • This is the expected behaviour. CORS checks are always carried out by browsers, but tools like Postman and curl do not make CORS checks.

    The CDK's ApiGatewayV2 HttpApi Construct supports access control. The ApiGateway RestApi has broader auth capabilities, including API Keys.