Search code examples
javascriptiframehttp-headerscontent-security-policy

Enforcing a web page to be iframed?


I have an HTML page that is designed to be iframed into a different website.

With a CSP frame-ancestors directive I can restrict in which pages it is allowed to be iframed. This disallows iframing into the wrong site which is the intent of this security policy.

In my scenario I also want to block loading this page stand alone because it does not make sense and will confuse people trying to interact with it. It only should be used in the iframed context.

As far as I can tell CSP does not have an option to block a page from being run standalone. It works as a whitelist so I can only allow more iframes and not deny something.

So far I have only found client-side solutions (like this which uses JavaScript) to detect this in the browser and then do something. Although this is a viable solution I prefer already blocking this at the server end.

I have had a look at the request headers and found that only on the first request the "Referer:" seems to be 'usable' but not reliable.

So my question is if it is possible to detect/block this serverside or is there a way to make the browser block this (similar to a CSP)? Or is the JavaScript route really the only current way to handle this?


Solution

  • The simplest option is to look for the request header and value:

    Sec-Fetch-Dest: iframe

    I have tested this on recent versions of Chrome, Edge, Firefox and Safari which covers my entire user population.

    I can easily verify the presence of this value and provide an error page if it is not present.