javascriptiframecontent-security-policysame-origin-policy

CSP frame-ancestors self directive blocks page served from same origin


I have a nodejs app which serves index.html for "/" route test.html for "/test" route

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname + "/index.html"));
});

app.get("/test", (req, res) => {
  res.sendFile(path.join(__dirname + "/test.html"));
});

index.html has an iframe which embeds /test as below

   <iframe
        width="100%"
        height="500px"
        src="http://localhost:5500/test"
        sandbox
      ></iframe>

In server.js, I am applying CSP as below:

app.use(function (req, res, next) {
  res.setHeader("Content-Security-Policy", "frame-ancestors self");
  next();
});

The content from /test route is blocked by Chrome saying enter image description here

As per MDN for frame-ancestors, enter image description here

The URL scheme and port are same for both are same i.e. http://localhost:5500

Host: enter image description here

Content being iframed can be access independently: enter image description here

Why is http://localhost:5500/test not being considered as sameorigin when compared to http://localhost:5500?

Minimal reproducible example - https://github.com/phalgunv/csp-demo-same-origin


Solution

  • Try surrounding "self" in single quotes:

    res.setHeader("Content-Security-Policy", "frame-ancestors 'self'");