After a fielding a few questions about security in some recent projects, I was looking at couple of ways that security is handled within the .NET framework. I wanted to figure out how you could define, method by method, whether a user had permission to run a method within their security context..

The two methods I focused on are Windows Principal and Principal Permission.

Windows Principal
At a basic level we could implement code that verifies what role the current user is based upon. This method is clean and simple! Throw this at the front of each method and your golden ... but that is not very elegant.

WindowsIdentity ident = WindowsIdentity.GetCurrent();
WindowsPrincipal user = new WindowsPrincipal(ident);
if(user.IsInRole("Admin")){
    //Do stuff here...
}

The Principal Permission
In the following example we have applied PrincipalPermissionAttribute which declaratively requires the user running the code to belong to a specific role or to have already have been authenticated. I learned the hard way that you also need to explicitly set the Principal Policy before calling the method or class with a permission attribute.

    using System.Security;
    using System.Security.Permissions;
    using System.Security.Principal;
    using System.Threading;
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

                MyTest mt = new MyTest();
                Console.WriteLine(mt.GetMessage());
            }
            catch(SecurityException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }

    class MyTest
    {
        public MyTest() {Console.WriteLine("Start MyTest"); }

        [PrincipalPermissionAttribute(SecurityAction.Demand, Name = @"Domain\Admin")]
        public string GetMessage()
        {
            return "My Message";
        }
    }