Export (0) Print
Expand All

PrincipalPermission Objects

The role-based security model supports a permission object similar to the permission objects found in the code access security model. This object, PrincipalPermission, represents the identity and role that a particular principal class must have to run. You can use the PrincipalPermission class for both imperative and declarative security checks.

To implement the PrincipalPermission class imperatively, create a new instance of the class and initialize it with the name and role that you want users to have to access your code. For example, the following code initializes a new instance of this object with an identity of "Joan" and a role of "Teller".

String id = "Joan";
String role = "Teller";
PrincipalPermission principalPerm = new PrincipalPermission(id, role);

You can create a similar permission declaratively using the PrincipalPermissionAttribute class. The following code declaratively initializes the identity to "Joan" and the role to "Teller".

[PrincipalPermissionAttribute(SecurityAction.Demand, Name = "Joan", Role = "Teller")]

When the security check is performed, both the specified identity and role must match for the check to succeed. However, when you create the PrincipalPermission object, you can pass a null identity string to indicate that the identity of the principal can be anything. Similarly, passing a null role string indicates that the principal can be a member of any role (or no roles at all). For declarative security, the same result can be achieved by omitting either property. For example, the following code uses the PrincipalPermissionAttribute to declaratively indicate that a principal can have any name, but must have the role of teller.

[PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Teller")]
Show:
© 2014 Microsoft