Skip to content

Instantly share code, notes, and snippets.

@ryanvgates
Last active December 7, 2015 05:19
Show Gist options
  • Save ryanvgates/7abf9afedd7a3e52d650 to your computer and use it in GitHub Desktop.
Save ryanvgates/7abf9afedd7a3e52d650 to your computer and use it in GitHub Desktop.
HttpModule for handling IFrame
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 Dispose() {}
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