This article has been
excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors
of C# Corner.
You can place security attributes in your classes or methods to assert, demand,
deny, or permit only certain permissions.
There can be zero or more public properties set in the attribute, each separated
by a comma. For example, the FileIOPermissionAttribute has properties for
controlling how a user can append, read, and write to a file. Setting these
properties in this attribute defines which files or directories you wish to
check for access permissions.
In Listing 22.22, FileIOPermissionAttribute demands permission to read C:\dir1\
whenever a method in MyClass is called. The EnvironmentPermissionAttribute
demands permission for reading the TEMP environment variable before a call to
MyMethod can succeed. If either of the demands fails, the system throws a
security exception for calls to MyMethod.
Listing 22.22: PermissionAttribute Example
// PermissionAttribute for class and method
[FileIOPermissionAttribute(SecurityAction.Demand,
Read = @"c:\dir1\")]
public
class
MyClass
{
[EnvironmentPermissionAttribute(SecurityAction.Demand,
Read = "TEMP")]
public void
MyMethod()
{
}
}
In Listing 22.23, AnyClass defines two assembly permission set attributes, which
will cause it to request to read, at a minimum, the minimum_permission.xml file
and, optionally, the optional_permission.xml file.
Listing 22.23: PermissionSetAttribute Example
// PermissionSetAttribute
[assembly:
PermissionSetAttribute(SecurityAction.Request.Minimum,
File = "minimum_permission.xml")]
[assembly:
PermissionSetAttribute(SecurityAction.RequestOptional,
File = "optional_permission.xml")]
public
class
AnyClass
{
public static
void Main()
{
Console.WriteLine("Permissions");
}
}
Listing 22.24 illustrates the declarative use of Deny to override security
checks. RegistryPermissionAttribute includes a SecurityAction enumeration for
Deny and the registry key to which write access will be denied.
Listing 22.24: RegistryPermissionAttribute Example
// Declarative demand1


Join the conversation! Your thoughts help the community grow.