nelmio / NelmioCorsBundle

Adds CORS (Cross-Origin Resource Sharing) headers support in your Symfony application
https://symfony.com/bundles/NelmioCorsBundle/
MIT License
1.89k stars 108 forks source link

nelmio_cors and varnish #123

Closed grekpg closed 4 years ago

grekpg commented 5 years ago
nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['*'] dont work with varnish - it set first domain
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/api/': ~

I use varnish cache - when open cachable api request on first domain - i get in response headers

Accept-Ranges: bytes Access-Control-Allow-Origin: http://app.local Access-Control-Expose-Headers: link Age: 12 Cache-Control: public Connection: keep-alive Content-Length: 6722 Content-Type: application/json Date: Thu, 21 Mar 2019 12:09:28 GMT Expires: Fri, 22 Mar 2019 00:00:00 GMT Server: nginx/1.10.3 (Ubuntu)

so varnish save this header , when i open this page from other domain - have ....as been blocked by CORS policy: The 'Access-Control-Allow-Origin'...

NelmioCorsBundle - return refferer page ? when i have * ?

rvanlaak commented 4 years ago

This is a valid point. We are also facing this but then with Symfony's HTTP Cache kernel.

We configured a proper CORS policy, but as the HTTP Cache returns a valid cache hit when the origin is different this leads to errors on the client side.

Using forced_allow_origin_value to force the value to * would solve this, but that would not be the right solution as it would invalidate our entire CORS policy.

rvanlaak commented 4 years ago

Update: response headers also get cached. Make sure to include the right differentiators to the response Vary header.

In this case Origin should also get included, because this bundle uses it to calculate the CORS response headers.

adri commented 4 years ago

@rvanlaak I'm having the same issue. How did you add the Vary header when a specific Access-Control-Allow-Origin is returned? In this bundle or did you go with your own solution?

rvanlaak commented 4 years ago

I will file a PR for this. Origin should get added to the Vary header in case the response is cacheable.

The solution for Symfony would be to add a event subscriber that subscribes to KernelEvents::RESPONSE.

rvanlaak commented 4 years ago

@adri created PR #156 , can you see if that branch fixes your use case as well?

adri commented 4 years ago

@rvanlaak Thanks a lot! I actually ended up implementing CORS in a load balancer. Also to unload PHP from dealing with OPTIONS requests. I think your PR is super helpful though. Hope it gets merged 🙏