Freigeben über


Declarative Security 

Declarative security syntax uses attributes to place security information into the metadata of your code. Attributes can be placed at the assembly, class, or member level, to indicate the type of request, demand, or override you want to use. Requests are used in applications that target the common language runtime to inform the runtime security system about the permissions that your application needs or does not want. Demands and overrides are used in libraries to help protect resources from callers or to override default security behavior.

In order to use declarative security calls, you must initialize the state data of the permission object so that it represents the particular form of permission you need. Every built-in permission has an attribute that is passed a SecurityAction enumeration to describe the type of security operation you want to perform. However, permissions also accept their own parameters that are exclusive to them. For a complete description of the parameters specific to permissions, see the section describing built-in permissions.

The following code fragment shows declarative syntax for requesting that your code's callers have a custom permission called MyPermission. This permission is a hypothetical custom permission and does not exist in the .NET Framework. In this example, the declarative call is placed directly before the class definition, specifying that this permission be applied to the class level. The attribute is passed a SecurityAction.Demand structure to specify that callers must have this permission in order to run.

<MyPermission(SecurityAction.Demand, Unrestricted = True)> Public Class MyClass1
   
   Public Sub New()
      'The constructor is protected by the security call.
   End Sub
   
   
   Public Sub MyMethod()
      'This method is protected by the security call.
   End Sub
   
   
   Public Sub YourMethod()
      'This method is protected by the security call.
   End Sub
End Class
[MyPermission(SecurityAction.Demand, Unrestricted = true)]
public class MyClass
{
   public MyClass()
   {
      //The constructor is protected by the security call.
   }

   public void MyMethod()
   {
      //This method is protected by the security call.
   }

   public void YourMethod()
   {
      //This method is protected by the security call.
   }
}

See Also

Reference

SecurityAction

Concepts

Security Syntax
Security Permissions

Other Resources

Extending Metadata Using Attributes
Code Access Security
Metadata and Self-Describing Components