What is Code Access Security in .NET ?

This article is an introduction to the Code Access Security in .NET Framework .

What is Code Access Security in .NET ?

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 runtime verifies 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 permissions allows you to access printer.
  • SqlClientPermission
  • Registry permission is 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 :

FileIOPermission objPermission = new FileIOPermission

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

public void Check() 
FileIOPermission obj =  new FileIOPermission(FileIOPermissionAccess.Read,@"C:\test.txt"); 
   obj. PermitOnly (); 
catch (SecurityException ex) 
// Incorrect permission process 

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() 

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 .

Copy link
Powered by Social Snap