Code Access
Code Access Security Facts
Code access security restricts the resources a particular piece of code can access, thus protecting the system from untrusted or possibly buggy code. Code access security allows varying degrees of trust to be applied to those code segments.
As with role-based security, code-access security follows two models: imperative and declarative. These models reflect the models of the role-based security, namely, imperative security demands and permissions are made in the code, while declarative demands and permissions are attributes which are tagged onto assemblies, classes and members.
There are a number of classes that you can use in the imperative model, each inherits from System.Security.CodeAccessPermission. To use imperative code-access security, select the class that best fits your needs, or create your own custom permission class by inheriting from System.Security.CodeAccessPermission. Common permissions include:
- DirectoryServicesPermission to control access to data in Windows Directory Service.
- FileIOPermission to control access to files.
- SqlClientPermission to control access to a SQL data source.
- RegistryPermission to control access to registry variables.
The following example defines an access level (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.
public void Process()
{
FileIOPermission fp =
new FileIOPermission(FileIOPermissionAccess.Read,
@"C:\");
try
{
fp.PermitOnly();
// Correct permission process
}
catch (SecurityException ex)
{
// Incorrect permission process
}
}
To used declarative code access security use one of the CodeAccessSecurityAttribute classes to tag an assembly, class or class member. There are a number of attribute classes that derive from System.Security.Permissions.CodeAccessSecurityAttribute. In fact, they basically mirror the CodeAccessSecurity classes.
Any assembly, class, or class member tagged with a CodeAccessSecurityAttribute must have the specified permission(s), otherwise a SecurityException will be thrown.
[FileIOPermissionAttribute(SecurityAction.PermitOnly,
Read=@"C:\")]
public void Process()
{
// process here
}
- - - - - S P O N S O R I N G A D V E R T I S M E N T - - - - -