How to use PrincipalPermission objects to evaluate authorization roles in ASP.NET in C#

You can use the PrincipalPermission approach described in the article How to use the PrincipalPermission Class to check authorization in ASP.NET in C# to evaluate more complex authentication rules.

For example, your application can have three users User1 , User2 and User3. By using the approach described in the article How to use IsInRole method to check authorization in ASP.NET in C#, you need to call IsInRole() triple. You can optimize your code by creating multiple PrincipalPermission objects and merge them to get one PrincipalPermission object. Then you can call Demand() on just this object.

The next example combines three roles:

 

try

{

PrincipalPermission pp1 = new PrincipalPermission(null,@”BUILTIN\Administrators”);

PrincipalPermission pp2 = new PrincipalPermission(null,@”BUILTIN\Guests”);

PrincipalPermission pp3 = new PrincipalPermission(null,@”BUILTIN\Users”);

 

// Combine these three permissions.

PrincipalPermission pp4 = (PrincipalPermission)pp1.Union(pp2);

pp4 = (PrincipalPermission)pp4.Union(pp3);

pp4.Demand();

// If the code reaches this point, the demand succeeded.

// The current user is in one of these roles.

}

catch (SecurityException err)

{

// The demand failed. The current user is in none of these roles.

}

 

This example checks that a user is a member of either one of the three Windows groups. You can also ensure that a user is a member of all three groups. In this case, use the PrincipalPermission.Intersect() method instead of PrincipalPermission.Union().