.net-coreiframex-frame-options

Allow site to be displayed in an iframe on another site


I want to display one of my sites (secondsite.com) in an iframe in one of my other sites (mainsite.com). On one of the pages of mainsite.com I have the following html:

<iframe src="https://secondsite.com"></iframe>

However, when I load up the page I get the following error in the console:

Refused to display 'https://secondsite.com' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

What do I need to add to the code in my secondsite project in order to display it in mainsite.com? And preferably only in mainsite.com.

As secondsite is a .NET Core 6 project, is there some configuration I can add to the Startup.cs/Program.cs to apply this to all pages?


In the end the solution was to put this in the program.cs file:

app.Use(async (context, next) =>
{
    context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'; frame-ancestors 'self' https://mainsite.com;");
    await next();
});

Solution

  • secondsite.com has the response header "X-Frame-Options: sameorigin" set, which only allows it to be framed by pages on the same origin. Mainsite.com is not the same origin and hence not allowed to frame it.

    You should remove X-Frame-Options as what you are trying to do is not supported with this header. Instead you should set the response header "Content-Security-Policy: frame-ancestors 'self' mainsite.com;". If you are not able to remove X-Frame-Options it is ok as it will be disregarded in the presence of CSP frame-ancestors.