X-Frame Options is a technology that helps prevent against clickjacking, clickjacking is a very clever hack as it fools the user into thinking they are clicking on a trusted link, when in fact they are actually clicking on a frame.

With X-Frame Options, you can instruct the browser to either allow or deny the page from being framed by using headers.

An issue arises when using Html.AntiForgeryToken() as this creates its own X-Frame as can be seen in the code below.

X Frame Options Same Origin Code Block
if (!_config.SuppressXFrameOptionsHeader)
            {
                // Adding X-Frame-Options header to prevent ClickJacking. See
                // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10
                // for more information.
                httpContext.Response.AddHeader("X-Frame-Options", "SAMEORIGIN");
            }

To solve this problem, I will show you two options.

The first option is to create a custom attribute, then create a master controller and allow all controllers that you require to inherit from it.

AntiForgeryConfig Suppress XFrame Options Header Code Block
using System;
using System.Web.Helpers;
using System.Web.Mvc;
namespace Web.Core.Helper
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class SuppressXFrameOptionsHeadersAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
        }
    }
}
//BaseController
[SuppressXFrameOptionsHeaders]
    public class MasterController : Controller
    {
    }

The second option is a bit more 'blunt' in that we hard code the suppression in the view as such:


Response.Headers.Remove("X-Frame-Options")
@Html.AntiForgeryToken()

Now in the web.config file > CustomHeaders we can add<add name="X-Frame-Options" value="SAMEORIGIN" /> or if using nwebsec we can add x-Frame-Options policy="SameOrigin" />

This will allow us to protect the entire site but remove duplicate X-Frame Options.

Either option will solve the problem of removing the duplicate X-Frames Options. Which one you use is up to you.


Summary

I hope you found this blog useful, and if you have any questions, please use the form below.


Blog Form

 Please complete the required fields (*required)

 *
*