Skip to content

Instantly share code, notes, and snippets.

@lnicola
Created June 20, 2014 15:59
Show Gist options
  • Save lnicola/dd6cef22e340c1850968 to your computer and use it in GitHub Desktop.
Save lnicola/dd6cef22e340c1850968 to your computer and use it in GitHub Desktop.
ASP .NET authorization module that removes inaccessible controls from the rendered page
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AuthorizationTest.HttpModules
{
public class AuthorizationModule : IHttpModule
{
private HttpApplication application;
public void Init(HttpApplication context)
{
application = context;
application.PostMapRequestHandler += HttpApplication_PostMapRequestHandler;
}
public void Dispose()
{
application.PostMapRequestHandler -= HttpApplication_PostMapRequestHandler;
}
private void HttpApplication_PostMapRequestHandler(object sender, EventArgs e)
{
var page = application.Context.Handler as Page;
if (page == null)
return;
page.PreRender += new EventHandler(Page_PreRender);
}
private void Page_PreRender(object sender, EventArgs e)
{
var page = sender as Page;
var sw = System.Diagnostics.Stopwatch.StartNew();
EnforceAuthorization(page.Controls);
System.Diagnostics.Trace.WriteLine(sw.ElapsedMilliseconds);
page.PreRender -= Page_PreRender;
}
private void EnforceAuthorization(ControlCollection controls)
{
foreach (Control control in controls)
{
var webControl = control as WebControl;
if (webControl != null)
{
var feature = webControl.Attributes["feature"];
if (feature != null)
{
webControl.Visible = HasFeature(feature);
webControl.Attributes.Remove("feature");
}
}
EnforceAuthorization(control.Controls);
}
}
private bool HasFeature(string feature)
{
var features = new[] { "Foo", "Bar" };
return features.Contains(feature);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment