Share via


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!");
      }
    Public Shared Sub _
    <PrincipalPermissionAttribute(SecurityAction.Demand, Name := "MyUser", Role := "User")> _
    PrivateInfo()
    
        'Print secret data.
        Console.WriteLine(ControlChars.CrLf + "You have access to the private data!")
    End Sub

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!

See Also

Reference

PrincipalPermission

Concepts

Role-Based Security Checks