apigateway: add explicit support for CORS
Requirements
- [x]
resource.addCorsPreflight(options) - [x]
AllowOrigin - [x]
AllowHeaderswith defaults for API Gateway - [x]
AllowMethods - [x]
AllowCredentials - [x]
MaxAge - [x]
ExposeHeaders - [x] Conditional
Varyresponse 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
- Response headers in simple requests are out of scope.
Resources
- MDN
- SAM implementation
- Serverless Framework implementation
- API Gateway CORS Survival Guide
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.
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,
},
}]
}
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.
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.)
Thanks, that worked!
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
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!
I can't help but I am looking forward to awslabs/aws-cdk#1572 be resolved and merged.
@piotrkubisa thank you for the note and reference to the issue. I'll be keeping an eye out for that issue as well!
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?
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,
},
}]
})
}
Oh nice one, thanks :thumbsup:
This is not working. Broken in 0.37.0 ?
What is not working? What is the error you are seeing?
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,
},
}]
})
}
Works like a charm
Just curious why it's MockIntegration. It feels weird to put that in a production config
@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)
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,
}
}]
})
}
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
S3 CORS support: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html