I am developing an ASP.NET MVC application which needs to be loaded inside an iframe
in another website. But the login page just won't appear inside the iframe
because an Header is being sent in the response X-Frame-Options
which is set to SAMEORIGIN
. Browser is not displaying the page in iframe
because of this. I already Googled and tried multiple things but nothing worked.
I am using ASP.NET forms authentication. May be in this case IIS adds this header in login page for added security. But I need to get rid of this in my use case.
I tried adding a custom header
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="ALLOW" />
</customHeaders>
</httpProtocol>
But the SAMEORGIN
is still being added in the header with comma.
I also tried adding Header value from C# using Response.Headers["X-Frame-Options"] = "ALLOW"
. It cause two headers with the same name.
I also tried this in web.config
<customHeaders>
<remove name="X-Frame-Options" />
</customHeaders>
It also didn't worked.
MVC 5 automatically adds an X-Frame-Options Header, so go to your Global.asax
file and add this to the Application_Start()
method:
System.Web.Helpers.AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
Please note that especially for a login page it is bad practice to remove this header, because it opens up your site for login credentials phishing attacks. So if this site of yours is publicly accessable I strongly recommend to keep this header.
Old question, but for other people searching for similar question, you can remove the X-Frame-Options
in specific actions using the following solution:
First, add this code to method Application_Start
in Global.asax.cs
(as @Florian Haider said):
System.Web.Helpers.AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
This will suppress the header in all actions. Add a new file named NoIframeAttribute.cs
containing the following code:
using System.Web.Mvc;
namespace MyApplication
{
public class NoIframeAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN");
}
}
}
Add the following line to RegisterGlobalFilters
method in FilterConfig.cs
:
filters.Add(new NoIframeAttribute());
Now, we have the header added to all actions again. But now we can remove it when needed. Just add the following line wherever needed:
Response.Headers.Remove("X-Frame-Options");