Skip to content

Instantly share code, notes, and snippets.

@ryanvgates
Last active April 6, 2018 04:35
Show Gist options
  • Save ryanvgates/85b605d9adde8cf330a7083ad5862410 to your computer and use it in GitHub Desktop.
Save ryanvgates/85b605d9adde8cf330a7083ad5862410 to your computer and use it in GitHub Desktop.
No IFrame For You
using System;
using System.Linq;
using System.Web;
using System.Configuration;
namespace XFrameOptionsHttpModule
{
public class XFrameOptionsHeaderModule : IHttpModule
{
private HttpApplication context;
private const string XFrameOptionsHeader = "X-Frame-Options";
private const string XFrameOptionsSameOrigin = "SAMEORIGIN";
public void Init(HttpApplication context)
{
this.context = context;
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
void OnPreSendRequestHeaders(object sender, EventArgs e)
{
try
{
if (context != null && context.Request != null && IsAllowedToIFrame(context.Request.UrlReferrer, (ConfigurationManager.AppSettings["UrlsAlowedToIFrame"] ?? string.Empty).ToString()))
{
context.Response.Headers.Set(XFrameOptionsHeader, string.Format("ALLOW-FROM {0}", context.Request.Url.GetLeftPart(UriPartial.Authority)));
}
else
{
context.Response.Headers.Set(XFrameOptionsHeader, XFrameOptionsSameOrigin);
}
}
catch (Exception exception)
{
//In case there is a failure due to misconfiguration, default it to SAMEORIGIN
context.Response.Headers.Set(XFrameOptionsHeader, XFrameOptionsSameOrigin);
}
}
private bool IsAllowedToIFrame(Uri urlReferrer, string allowedUrls)
{
var urlReferrerIsNull = urlReferrer == null;
var url = urlReferrerIsNull ? string.Empty : urlReferrer.Authority;
var requestUrlIsEmpty = urlReferrerIsNull || string.IsNullOrEmpty(url);
var isAllowed = allowedUrls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList().Contains(url);
return !requestUrlIsEmpty && isAllowed;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment