Geeks With Blogs
Blog Moved to Blog Moved to
In my coding, I've always been careful about which operations are permitted and which are not.  I took a lot of lessons learned when I studied for and passed 70-340 Implementing Security for Applications with Microsoft Visual C# .NET.  Anyhow, I want to run through a few examples of what I have been doing as a best practice.  As I go along in time, I'll run through more useful examples and how they apply to the enterprise.  Believe me, in the world today, companies are becoming increasingly interested in security.
First, let's start off with some basic authentication.  In this first example, we want to make sure that the current user is authenticated in order to create my custom class.
Before anything can begin, we need to make sure that the AppDomain is using WindowsPrincipal, so this code is needed:
Next, we will use attributes to require that the user be authenticated.  By using the PrincipalPermissionAttribute class, we can demand that the user be authenticated in order to use this JobManager class.
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public class JobManager
} // class- JobManager
Let's take this a little further.  For example, we need to expose a method to delete a job by an ID, but we need to lock this down to the local Administrators group.  Here is how we'd accomplish that task:
[PrincipalPermission(SecurityAction.Demand, Authenticated=true, Role=@"BUILTIN\Administrators")]
 public void DeleteJob(Guid id)
} // method - DeleteJob
 There are also some times when using attributes isn't quite enough.  In this example, if the enum parameter is set to a particular value, then we must check if the user is a local administrator.  This is how we'd accomplish that:
public enum JobOwner
} // enum - JobOwner
public ReadOnlyCollection<Job> GetJobs(JobOwner owner)
     // Validate arguments
     if(!Enum.IsDefined(typeof(JobOwner), owner))
          throw new InvalidEnumArgumentException("owner", (int)owner, typeof(JobOwner));
     // Check if owner is set to all users
     if (owner == JobOwner.Allusers)
         // Get current principal
         WindowsPrincipal currentPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
         // Check if part of BUILTIN\Administrators
         if (!currentPrincipal.IsInRole(@"BUILTIN\Administrators"))
             throw new SecurityException("User must be an administrator of the local machine");
         } // if - owner
} // method - GetJobs
So, we've barely scratched the surface, and in the coming days and weeks, I'll go more into what we can with this stuff, so stay tuned...
Posted on Monday, May 8, 2006 3:10 PM Microsoft , .NET , Enterprise Architecture , MCP , C# | Back to top

Comments on this post: .NET Code Access Security for fun and profit

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Matthew Podwysocki | Powered by: