question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

apigateway: add explicit support for CORS

See original GitHub issue

Requirements

  • resource.addCorsPreflight(options)
  • AllowOrigin
  • AllowHeaders with defaults for API Gateway
  • AllowMethods
  • AllowCredentials
  • MaxAge
  • ExposeHeaders
  • Conditional Vary response header
  • Configure response status code (should default to 204)
  • Support proxy and non-proxy resources
  • Support multiple origins through velocity templates (like in serverless framework).
  • Automatically discover allowed methods by default based on model.
  • Recursive (apply to all child resources)
  • 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.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:33 (9 by maintainers)

github_iconTop GitHub Comments

6reactions
hvitalcommented, Jul 9, 2019

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,
        },  
        }]
    })
}
6reactions
kennucommented, Nov 7, 2018

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.)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Configuring CORS for an HTTP API - Amazon API Gateway
The $default route catches requests for all methods and routes that you haven't explicitly defined, including OPTIONS requests. To support unauthorized OPTIONS ...
Read more >
Your Complete API Gateway and CORS Guide
In brief, what we're going to need to do to support CORS is to add an HTTP OPTIONS method for each of our...
Read more >
Adding CORS support to API Deployments - Oracle Help Center
This topic describes how to use a request policy to add CORS support to API deployments with Oracle Cloud Infrastructure API Gateway.
Read more >
Your CORS and API Gateway survival guide
If you want the quick and dirty way to solve CORS in your Serverless application, do this. To handle preflight requests, add the...
Read more >
How to handle CORS | CORS - Amazon HTTP API p9 - YouTube
Welcome to part 9 of the new tutorial series on Amazon HTTP API. In this video, we will cover how to handle CORS...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found