In this short jumpstart, I am going to show how to prevent loading of an ASP.Net MVC page in a cross domain iframe using traditional HttpModules. We use HTTP header “X-Frame-Options” to prevent the loading of page in iframe, but instead of injecting this header on every code file, we use a HttpModule to configure this header as a site wide option. Here we use X-Frame-Options to “Same Origin” so that iframe requests from same domain will be served and rest all ignored.
X-Frame-Options does support couple of other values – DENY and ALLOW-FROM. When set to deny, all the requests even from the same origin will be denied, that means applications pages can never be loaded in any iframe. Allow-from will make the application pages available to only the iframes which are hosted on specific pages with URL specified in Allow-from.
Lets get started by creating an MVC5 application in Visual Studio 2013.

Create a HttpModule as shown below.
using System; using System.Web; namespace WebApplication2 { public class CustomResponseHeadersModule : IHttpModule { public void Init(HttpApplication context) { context.PreSendRequestHeaders += new EventHandler(ctx_PreSendRequestHeaders); } void ctx_PreSendRequestHeaders(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; context.Response.AddHeader("X-Frame-Options", "SAMEORIGIN"); } public void Dispose() { this.Dispose(); } } }
Add the created HttpModule in the System.webServer node of Web.Config file.
<system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="CustomResponseHeadersModule" /> <add name="CustomResponseHeadersModule" type="WebApplication2.CustomResponseHeadersModule" /> <remove name="FormsAuthenticationModule" /> </modules> </system.webServer>
Now lets run the application by click F5.

Use the URL and create a simple html page to test the loading of the application in iframe. Have the following html in the created sample page.
<head> </head> <body> <iframe src='http://localhost:47874/'></iframe> </body>
Open the page in browser, and iframe will not be loaded with application home page.

Now lets comment out the X-Frame-Options HTTP header and re-run the application. When we go to the iframe page, it will not show the application page because we do not have X-Frame-Options in the page.

Happy Coding!!!






Pingback: TechNet Blogs()