aws-cdk icon indicating copy to clipboard operation
aws-cdk copied to clipboard

apigateway: add explicit support for CORS

Open eladb opened this issue 8 years ago • 33 comments

Requirements

  • [x] resource.addCorsPreflight(options)
  • [x] AllowOrigin
  • [x] AllowHeaders with defaults for API Gateway
  • [x] AllowMethods
  • [x] AllowCredentials
  • [x] MaxAge
  • [x] ExposeHeaders
  • [x] Conditional Vary response header
  • [x] Configure response status code (should default to 204)
  • [x] Support proxy and non-proxy resources
  • [x] Support multiple origins through velocity templates (like in serverless framework).
  • [ ] Automatically discover allowed methods by default based on model.
  • [x] Recursive (apply to all child resources)
  • [x] LambdaRestApi (apply a CORS policy to all routes)
  • [ ] CORS with custom authorizers (good post) through AWS::ApiGateway::GatewayResponse

Nice to Have

  • [ ] Dynamic CORS handler? (through a Lambda proxy and Access-Control-Max-Age=0)

Non-Requirements

Resources

Notes

Coming from stack overflow

Note that we get a lot of confusion around this since it only configures the Preflight request. Customers expect it to be a magic setting for enabling CORS headers on their Lambda responses. We cant do this because API Gateway does not allow response header mapping for Lambda proxy. Might be better to call this CorsPreflight? At minimum document it clearly.

eladb avatar Oct 11 '18 18:10 eladb

From @kennu:

function addCorsOptions(apiResource: apigateway.IRestApiResource) {
  const options = 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}"
    },
  }))
  const methodResource = options.findChild('Resource') as apigateway.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-Credentials': true,
      'method.response.header.Access-Control-Allow-Origin': true,
    },
  }]
}

eladb avatar Oct 24 '18 09:10 eladb

I am also currently struggling with this. How do you actually use the provided code snippet? Add it to the root of the api? Or for every Resource I want to enable CORS for? I currently have something like:

const blog_api = new apigw.RestApi(this,"Blog-Rest-Api");
const blogs =  blog_api.root.addResource('blogs');

const blog  = blogs.addResource('{blog_id}');
const addBlog = blogs.addResource('add');

// A get to blogs just returns all blogs
const getBlogsIntegration = new apigw.LambdaIntegration(getBlogsHandler);
blogs.addMethod('GET',getBlogsIntegration);

// A get to blogs/id gets only the one blog with the specific id 
const getBlogIntegration = new apigw.LambdaIntegration(getBlogHandler);
blog.addMethod('GET',getBlogIntegration);

With what variables to I have to call addCorsOptions and at which point? I tried on the root and on blogs, but couldn't get it to work yet.

FinnIckler avatar Nov 07 '18 14:11 FinnIckler

I have attached it to the API root and any resource paths like this:

    const api = new apigateway.RestApi(this, 'Api', { ... })
    addCorsOptions(api.root)

    const apiContacts = api.root.addResource('contacts')
    addCorsOptions(apiContacts)

You should be able to verify after deployment in API Gateway Console that everything is present.

But you also need to return an Access-Control-Allow-Origin header from your Lambda, because API Gateway doesn't add that automatically to the responses. The addCorsOptions() function here only adds a separate OPTIONS method and its headers.

(I do wish API Gateway could handle all of this automagically with a single enable option.. It's been very complicated from the beginning.)

kennu avatar Nov 07 '18 15:11 kennu

Thanks, that worked!

FinnIckler avatar Nov 08 '18 08:11 FinnIckler

Example provided by @kennu stopped working for the latest version of the CDK. However, after some changes following code is working for me:

function addCorsOptions(apiResource: apigateway.IRestApiResource) {
  const options = 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}"
    },
  }))
  const methodResource = (options as cdk.Construct).node.findChild("Resource") as apigateway.CfnMethod
  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-Credentials': true,
      'method.response.header.Access-Control-Allow-Origin': true,
    },
  }]
}

As a hint if you get 500 status on OPTION methods is to set following in the MockIntegration definition (it is a common error if you are using compression over API Gateway):

contentHandling: apigateway.ContentHandling.ConvertToText

piotrkubisa avatar Jan 18 '19 09:01 piotrkubisa

Hello, I am trying to implement something similar, but in Java. I unfortunately cannot get past the const methodResource = (options as cdk.Construct).node.findChild("Resource") as apigateway.CfnMethod piece of this code.

The Java implementation is not letting me cast the cdk.Construct to an apigateway.CfnMethod.

Any Java experts out there who might be able to lend a hand?

Thanks in advance!

wmunyan avatar Jan 18 '19 20:01 wmunyan

I can't help but I am looking forward to awslabs/aws-cdk#1572 be resolved and merged.

piotrkubisa avatar Jan 19 '19 13:01 piotrkubisa

@piotrkubisa thank you for the note and reference to the issue. I'll be keeping an eye out for that issue as well!

wmunyan avatar Jan 19 '19 17:01 wmunyan

The propertyOverrides.methodResponses option no longer works after the refactor: readonly struct properties and hide internals PR.

I'm not really sure how to work around this now.

Any ideas?

justinThompson avatar Apr 02 '19 14:04 justinThompson

I think you can now specify the method responses as an option to addMethod()

export function addCorsOptions(apiResource: apigateway.IRestApiResource) {
  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,
      },  
    }]
  })
}

kennu avatar Apr 07 '19 02:04 kennu

Oh nice one, thanks :thumbsup:

justinThompson avatar Apr 07 '19 11:04 justinThompson

This is not working. Broken in 0.37.0 ?

sankeyraut avatar Jul 06 '19 12:07 sankeyraut

What is not working? What is the error you are seeing?

eladb avatar Jul 07 '19 17:07 eladb

Just a few edits:

  • Rename IRestApiResource to IResource
  • Rename apigateway.PassthroughBehavior.Never to apigateway.PassthroughBehavior.NEVER
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,
        },  
        }]
    })
}

hvital avatar Jul 09 '19 07:07 hvital

Works like a charm

sankeyraut avatar Jul 10 '19 18:07 sankeyraut

Just curious why it's MockIntegration. It feels weird to put that in a production config

vegetabill avatar Aug 19 '19 23:08 vegetabill

@eladb I'm using LambdaRestApi and when I try to add this - it simply remove the lambda integration.... how to add CORS in this case ?

const APIGW = new apigw.LambdaRestApi(this, 'ListBranchesAPIGW', { handler: FUNCTION, apiKeySourceType: apigw.ApiKeySourceType.HEADER, restApiName: 'ListBranchesAPI', deployOptions: { stageName: 'prod' }, defaultMethodOptions: { apiKeyRequired: true }, proxy: true
}); addCorsOptions(APIGW.root)

ghost avatar Aug 28 '19 03:08 ghost

thanks every one on this thread for the code samples. Finally, I successfully, deployed an API Gateway + Lambda Proxy with COGNITO Authorizer - sharing the code - might help someone who lands here..

    // construct: lambda
    const FUNCTION = new lambda.Function(this, 'ListBranchesHandler', {
      runtime: lambda.Runtime.NODEJS_10_X,
      code: lambda.Code.asset('lib/list-branches/function'), // your function directory
      handler: 'list-branches.handler'
    });
    // construct: apigw
    const APIGW = new apigw.LambdaRestApi(this, 'ListBranchesAPIGW', {
      handler: FUNCTION, // attaching lambda function
      apiKeySourceType: apigw.ApiKeySourceType.HEADER,
      restApiName: 'ListBranchesAPI',
      deployOptions: { stageName: 'prod' },
      defaultMethodOptions: {
        apiKeyRequired: false
      },
      proxy: false
    });
    // --> defining an authorizer COGNITO
    const authorizer = new CfnAuthorizer(this, 'CognitoAuth', {
      restApiId: APIGW.restApiId.toString(),
      type: apigw.AuthorizationType.COGNITO,
      identitySource: 'method.request.header.Authorization',
      name: 'CognitoAuthName',
      providerArns: ['ARN OF COGNITO USER POOL']
    })
    // --> defining an authorizer COGNITO
 const resource = APIGW.root.addResource('branches') // creating a resource
    addCorsOptions(resource) // adding OPTION for CORS
    // --> adding the authorizer
    const method = resource.addMethod('GET', undefined, {
      // apiKeyRequired: true, // enable this if you need API key
      authorizationType: apigw.AuthorizationType.COGNITO,
      authorizer: {authorizerId: authorizer.ref}
    })
     // --> adding the authorizer
    function addCorsOptions(apiResource: apigw.IResource) {
      apiResource.addMethod('OPTIONS', new apigw.MockIntegration({
        integrationResponses: [{
          statusCode: '200',
          // contentHandling: apigw.ContentHandling.CONVERT_TO_TEXT,
          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-Origin': "'*'",
            'method.response.header.Access-Control-Allow-Credentials': "'false'",
            'method.response.header.Access-Control-Allow-Methods': "'GET,OPTIONS'", // modify this based on methods
          }
        }],
        passthroughBehavior: apigw.PassthroughBehavior.WHEN_NO_MATCH,
        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, // COGNITO
            'method.response.header.Access-Control-Allow-Origin': true,
          }

        }]
      })
    }

ghost avatar Aug 29 '19 13:08 ghost

thanks every one on this thread for the code samples. Finally, I successfully, deployed an API Gateway + Lambda Proxy with COGNITO Authorizer - sharing the code - might help someone who lands here..

// --> defining an authorizer COGNITO
const authorizer = new CfnAuthorizer(this, 'CognitoAuth', {
  restApiId: APIGW.restApiId.toString(),
  type: apigw.AuthorizationType.COGNITO,
  identitySource: 'method.request.header.Authorization',
  name: 'CognitoAuthName',
  providerArns: ['ARN OF COGNITO USER POOL']
})

@smfontevan, this is super helpful. I have a CFn stack where I assign a function to each resource's method (or at least to each resource), but the [LambdaRestApi] construct (https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_apigateway/LambdaRestApi.html) wasn't getting me there. I don't work with API Gateway a lot, so seeing your JS code was helpful. While converting to Python, the Cognito authorizer above wasn't working. I noticed in the CloudFormation definition that type should be TOKEN, 'COGNITO_USER_POOLS, or 'REQUEST.

Haven't fully tested yet (waiting on CloudFront distro delete/create), but this has helped understand the non-swagger/AWS:SERVERLESS was of creating an API gateway.

EDIT: code formatting

gadams999 avatar Sep 03 '19 00:09 gadams999

S3 CORS support: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html

eladb avatar Sep 20 '19 06:09 eladb