Home > OS >  Unexpected behaviour of Access-Control-Allow-Origin when tested locally
Unexpected behaviour of Access-Control-Allow-Origin when tested locally

Time:11-29

I'm running an NGINX web server locally and I don't understand why, despite the presence of access-control-allow-origin: www.site-A.test in the response, a page of origin www.site-B.test is still allowed to load resources from origin www.site-A.test.

I expected that video file at www.site-A.test not to play anywhere other than www.site-A.test. That is not the behaviour I observe locally.

Both sites are locally running on macOS on NGINX 1.21.4 and in Docker environment. Tested in Firefox Developer Edition 95.


REPRODUCTION OF EXAMPLE
(actual hosts that I'm testing at)

nginx.conf

http {
    map $sent_http_content_type $cors {
        ~*video/ $scheme://$server_name;
    }
    # There are two more blocks that handle redirection to this server block
    server {
       listen 8443 ssl http2;
       listen [::]:8443 ssl http2;
       server_name www.nginx.test;

       # Access-Control-Allow-Origin
       add_header Access-Control-Allow-Origin $cors always;
    }
    # There are two more blocks that handle redirection to this server block
    server {
       listen 8443 ssl http2;
       listen [::]:8443 ssl http2;
       server_name www.nginx1.test;

       # Access-Control-Allow-Origin
       add_header Access-Control-Allow-Origin $cors always;
    }
}

Port 8334 is container's port. Both websites listen on 443 port.
In this scenario every content-type: video/mp4 is shareable only within host that a resource is coming from.

enter image description here

CodePudding user response:

What you're observing is expected behaviour. The premise of your question is incorrect: you can embed a video in your page using the <video> HTML element without needing the server to specifically allow your origin. See MDN's page about the Same-Origin Policy:

Here are some examples of resources which may be embedded cross-origin:

  • [...]
  • Media played by <video> and <audio>.

Cases where you do need the resource to be CORS-enabled are limited to when you want to use the video within a <canvas> element.

If you want to prevent third-party sites from embedding a video, you can implement some resource isolation policy on the server side.

  • Related