ASP.NET Security Principal Permission Attributes - SecurityAction.Demand Authenticated = true - Application_Error

I am working on a community website as a small project that allows any authenticated user to add news and events to the website. Although the community framework has support for roles, I don't see it being used very much.  Essentially you are either authenticated or not authenticated on the website and there is one role to speak of at this time “Admin”.  Pretty trivial, I know.

As I had mentioned earlier in the ASP.NET 2.0 Best Practices document, I like to use the Principal Permission Attributes on various classes any chance I get to keep things as secure as possible.  It seems like a fool proof way to ensure unauthorized access to certain functionality in your application.

If we want to keep unauthenticated users from accessing the EditEvent UserControl that embodies all the functionality to edit an event on the website, the security permissions on the UserControl can be as simple as this:

 

[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public class EditEvent : BaseUserControl
{
    // ...
}

 

If an unauthenticated user somehow gets access to this UserControl, ASP.NET will throw a Security Exception.

You will want to log this message in some type of event log so that you can fix the security breach at a later time:

 

void Application_Error(object sender, EventArgs e)
{
   //get reference to the source of the exception chain
   Exception ex = Server.GetLastError().GetBaseException();

   //log the details of the exception and page state to the
   //Event Log
   EventLog.WriteEntry("Community Website",
     "MESSAGE: " + ex.Message + 
     "\nSOURCE: " + ex.Source +
     "\nFORM: " + Request.Form.ToString() + 
     "\nQUERYSTRING: " + Request.QueryString.ToString() +
     "\nTARGETSITE: " + ex.TargetSite +
     "\nSTACKTRACE: " + ex.StackTrace, 
     EventLogEntryType.Error);

   //Optional email or other notification here...
}

The Princinpal Permission Attribute seems a lot cleaner than checking User.IsAuthenticated or other code equivalents.  You also get the added benefit of being able to use Reflection-based tools to help document the security in your applications.

 

posted on Friday, October 07, 2005 11:57 AM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices