Export (0) Print
Expand All

Performing Declarative Security Checks

Declarative demands for PrincipalPermission work the same way as declarative demands for code access permissions. Demands can be placed at the class level as well as on individual methods, properties, or events. If a declarative demand is placed at both the class and member level, the declarative demand on the member overrides (or replaces) the demand at the class level.

The following code example shows a modified version of the PrivateInfo method from the previous section's example. This version uses declarative security. The PrincipalPermissionAttribute defines the principal that the current thread must have to invoke the method. Simply pass SecurityAction.Demand with the name and role that you require.

      [PrincipalPermissionAttribute(SecurityAction.Demand, Name = "MyUser", Role = "User")]
      public static void PrivateInfo()
      {   
         //Print secret data.
         Console.WriteLine("\n\nYou have access to the private data!");
      }

This method throws a security exception if the current thread does not contain the proper principal. If the the user enters 1, the PrivateInfo method is invoked and the following message displays to the console.

You have access to the private data!
Show:
© 2014 Microsoft