The following code fragments show some example role checks using programmatic, declarative, and imperative techniques.
Authorizing Bob to perform an operation:
Note Although you can authorize individual users, you should generally authorize based on role membership, which allows you to authorize sets of users who share the same privileges within your application.
Direct user name check
GenericIdentity userIdentity = new GenericIdentity(“Bob”);
if (userIdentity.Name==”Bob”)
{
}
Declarative check
[PrincipalPermissionAttribute(SecurityAction.Demand,
User="Bob")]
public void DoPrivilegedMethod()
{
}
Imperative check
PrincipalPermission permCheckUser = new
PrincipalPermission(
“Bob”,
null);
permCheckUser.Demand();
Authorizing tellers to perform an operation:
Direct role name check
GenericIdentity userIdentity = new GenericIdentity(“Bob”);
// Role names would be retrieved from a custom data store
string[] roles = new String[]{“Manager”, “Teller”};
GenericPrincipal userPrincipal = new
GenericPrincipal(userIdentity,
roles);
if (userPrincipal.IsInRole(“Teller”))
{
}
Declarative check
[PrincipalPermissionAttribute(SecurityAction.Demand,
Role="Teller")]
void SomeTellerOnlyMethod()
{
}
Imperative check
public SomeMethod()
{
PrincipalPermission permCheck = new PrincipalPermission(
null,”Teller”);
permCheck.Demand();
// Only Tellers can execute the following code
// Non members of the Teller role result in a security
exception
. . .
}
Authorize managers OR tellers to perform operation:
Direct role name check
if (Thread.CurrentPrincipal.IsInRole(“Teller”) ||
Thread.CurrentPrincipal.IsInRole(“Manager”))
{
// Perform privileged operations
}
Declarative check
[PrincipalPermissionAttribute(SecurityAction.Demand,
Role="Teller"),
PrincipalPermissionAttribute(SecurityAction.Demand,
Role="Manager")]
public void DoPrivilegedMethod()
{
…
}
Imperative check
PrincipalPermission permCheckTellers = new
PrincipalPermission(
null,”Teller”);
PrincipalPermission permCheckManagers = new
PrincipalPermission(
null,”Manager”);
(permCheckTellers.Union(permCheckManagers)).Demand();
Authorize only those people who are managers AND tellers to perform operation:
Direct role name check
if (Thread.CurrentPrincipal.IsInRole(“Teller”) &&
Thread.CurrentPrincipal.IsInRole(“Manager”))
{
// Perform privileged operation
}
Declarative check
It is not possible to perform AND checks with .NET roles declaratively. Stacking PrincipalPermission demands together results in a logical OR.
Imperative check
PrincipalPermission permCheckTellers = new
PrincipalPermission(
null,”Teller”);
permCheckTellers.Demand();
PrincipalPermission permCheckManagers = new
PrincipalPermission(
null, “Manager”);