Search code examples
asp.net-mvc-5corssame-origin-policyx-frame-options

Same origin policy / CORS in MVC 5


What is the default policy within an asp.net mvc application? Also how are CORS and X-Frame-Options related?

If I create a new MVC web app (hosted in IIS) on port e.g. 21232, I add an iframe to the index views with a source set to my local IIS e.g.

<iframe src="http://localhost/iisstart.htm" width="800" height="100"/>

This works fine (even though on a different port to the web application).

If I now change the iframe source to be something completely external, e.g.

<iframe src="http://www.google.com" width="800" height="100"/>

This now displays an empty iframe. If I look in the Chrome dev tools (Chrome used in both examples) I see an error in the console

Refused to display 'https://www.google.co.uk' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

  1. Why did the first URL work when the address is on a different port to the hosting page?
  2. How do X-Frame-Options relate to CORS? I tried adding the following to my web.config (see ref enable cors in IIS)

<add name="Access-Control-Allow-Origin" value="*" />

Which made no difference. Looks as if I need to add the following to the Application_Start in the global.asax.cs

AntiForgeryConfig.SuppressXFrameOptionsHeader = true;

Are X-Frame-Options specifically iframe related?


Solution

  • I think you got the The X-Frame-Options response header and CORS all mixed up.

    The X-Frames-Options response header is used to indicate whether or not a browser should be allowed to load a particular page in a <iframe>. CORS on the other hand is used to determine if XMLHttpRequest(XHR) (and a few other things) is allowed across domains.

    So yes, X-Frames-Options are <iframe> realated only.

    The reason why you are able to load your page from http://localhost/iisstart.htm in you web application running at port 21232 is because there is no X-Frame-Options response header present in response. You will not be able http://www.google.com because its X-Frames-Options is set to SAMEORIGIN. This means unless your domain is google.com, you will not be able load it inside an <iframe>.

    The Access-Control-Allow-Origin header that you added has nothing to do with <iframe>. There is no way you will be able to load http://www.google.com in your page.