Using PricipalPermission for Declarative role based Authorization

I have developed a custom authentication and authorization solution built on IPrincipal and ASP.NET Forms authentication. I wanted to make sure that some data only were accessed by certain roles. I chose to use attribute based declarative access on the Facade class that wraps my Dataset. The PrincipalPermission attribute in the System.Security.Permissions namespace makes this really easy:

[PrincipalPermission(SecurityAction.Demand, Authenticated=true, Role = "Administrator")]

The question was how to do a logical OR on the role. This is even easier, just add two attributes:


[PrincipalPermission(SecurityAction.Demand, Authenticated=true, Role = "Administrator")]
[PrincipalPermission(SecurityAction.Demand, Authenticated=true, Role = "Moderator")]

The attributes can be set on class or method level. Setting class level to "Administrator" and "Moderator" will ensure that only users in one of these roles access the class. If you specify "Administrator" on method level it will override and make sure no "Moderator" users will access this method, even though they have class level access.

If your application tries to access these methods for a user that does not have any of these roles a System.Security.SecurityException will be thrown. Log the trespassing in the Global.asax Application_Error method like this:

protected void Application_Error(object sender, EventArgs e)
{
  Exception ex = Server.GetLastError();
  if(ex is System.Security.SecurityException)
  {
    Log.Write("Evil occured at " + Request.Path + ex.Message);
    Server.ClearError();
    Response.Redirect("SecurityBreach.aspx");
  }
}

Simple and really cool!

2 Comments

Comments have been disabled for this content.