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

You can use the PrincipalPermission approach described in the article How to use the PrincipalPermission Class to check authorization in ASP.NET in VB.NET 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 VB.NET, 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

Dim PP1 As PrincipalPermission = New PrincipalPermission(vbNull, “BUILTIN\Administrators”)

Dim PP2 As PrincipalPermission = New PrincipalPermission(vbNull, “BUILTIN\Guests”)

Dim PP3 As PrincipalPermission = New PrincipalPermission(vbNull, “BUILTIN\Users”)

‘ Combine these three permissions.

Dim PP4 As PrincipalPermission = DirectCast(PP1, PrincipalPermission).Union(PP2)

PP4 = DirectCast(PP4, PrincipalPermission).Union(PP3)

PP4.Demand()

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

‘ The current user is in one of these roles.

Catch ex As Exception

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

End Try

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().