This article is an introduction to the Code Access Security . Protecting resources from unauthorized use is what Code Access Security is all about . Both Role based and Code access security is based on the notion of the permissions. Permissions in the Role based security is about the authorized users to run the code. In Code access security, we authorize code to access resources.These are independent of the user who runs the code . Whenever a code is executed in .NET , the .NET runtimeverifies it based on the permissions and evidence ( place where the code came from ) . Some examples of Code Access Security are

Directory Services Permission allows you to access active directory.

File IO Permission gets the access to the File system.

Printing permissionsallows you to access printer.

SqlClientPermission

Registry permissionis the permission to access the registry. etc.

In CAS, what permissions are really all about is identifying the resources and trying to assess what kind of security level , code might have for that resource.The constructor of all the permissions are different . They are dependent on the type of resource that they are protecting.Eg :

Similar to Role based Security , the code access security also follows 2 models Imperative and declarativeThere are a few classes that you can use with the imperative model, which inherits from System.Security.CodeAccessPermission

The above example defines an (Read permission) and uses the PermitOnly method to check the user’s permissions.If permissions do not match those specified, a SecurityException will be thrown.The class member,method etc that is tagged with a CodeAccessSecurityAttribute must have the specified permissions, otherwise a SecurityException will be thrown.

public void Check1() { File.Create(@"E:\test.txt"); }

The above example denies the Write operations in the Drive “E” . So when an Write Operation is Executed , an Exception is thrown which denies the creation of the file test.txt .