Converting Declaractive PrincipalPermission to Programmatic .Demand

2.1k views Asked by At

I currently have two roles like this:

[PrincipalPermission(SecurityAction.Demand, Role="Domain\Admin")] [PrincipalPermission(SecurityAction.Demand, Role="Domain\AnotherRole")]

The problem is that this inherited code is specific to the domain, and I want to eventually get the roles from the web.config file, so I can work on a VM not in the domain.

I have seen an example like this:

PrincipalPermission permCheck = new PrincipalPermission(
                                     null, 
                                     @"Domain\Admin"); 
permCheck.Demand();

Since this throws an exception if user is not in role, how do I change this example to allow either of the two roles? I could use multiple IPrincipal.IsInRole() and then throw my own exception, but seems like there is probably a way to use the .Demand method with multiple roles.

Update 12/21: Sample Code based on Union link from Ladislav's answer below:

PrincipalPermission ppAdmin = new PrincipalPermission(null, @"Domain\Admin");
PrincipalPermission ppAnother = new PrincipalPermission(null, @"Domain\AnotherRole");
(ppAdmin.Union(ppAnother)).Demand();

But AzMan (suggested by Ladislav looks like a better but more involved solution).

1

There are 1 answers

2
Ladislav Mrnka On BEST ANSWER

PrincipalPermission has Union method. This method allows you combining several PrincipalPermissions before you call Demand. But instead of using imperative permissions you can check Authorization manager (AzMan) and related role provider (AuthorizationStoreRoleProvider). Authorization manager allows you defining abstract roles in your application and assign real user groups and roles through MMC.