Configurable PrincipalPermission attribute

I while ago, a question came up in the WCF Forum about configuring the role and/or user name properties of the PrincipalPermission attribute. As I answered, it is possible to create a custom version of the attribute (deriving from the CodeAccessSecurityAttribute, since the PrincipalPermission attribute is sealed) and pull the property values from the {web|app}.config file.

I implemented a solution for this about a year ago and planned to put up a blog post about it, but it never made it out to the public (the main cause is probably that I experienced a blog-block period of my life :-P).

The same requirement may be a viable solution i system I’m currently working on for a customer, so I dug through my archives and found the old code.

I’ve polished it a bit made it available here under the Apache License 2.0.

The extended version, PrincipalPermissionEx can be used in two modes; either as a “normal” derivable PrincipalPermission attribute or an attribute that uses the configuration system (or a combination of both).

Instead of using the generic PrincipalPermission attribute, you’ll make derived version for each system role with a sensible name – making it more reliable and resistant to typos; e.g.

[MustHaveSuperUserPrivilegesPermission]
public void PrivilegedOperation(…)
{
}

instead of:

[PrincipalPermission(Role = "MYDOMAIN\SuperUsers")]
public void PrivilegedOperation(…)
{
}


Take a look at the supplied sample code to see how this is implemented.

The usage of PrincipalPermission-based authorization is useful in a variety of scenarios; it can be applied to WCF services, ASP.NET & Smart Client applications. Note that if you put the user name/role in the configuration file, you will need to ensure that the file is locked down with an appropriate ACL to prevent tampering by malicious users. This might not apply to solutions hosted on a locked down server (i.e. IIS-hosted web applications and services) but for smart / desktop clients where the user might have higher privileges to files on the local file system it is necessary to be aware of this.

As always, feedback is welcome :-)

kick it on DotNetKicks.com

Be Sociable, Share!

  • http://twitter.com/windump ticktock

    in your opinion – would it be improper to declare a unique “role” for every single operation you want to restrict. This way the administrator has full granular control over the individuals and groups. Thoughts? Is there a better way – I like the AzMan concept where Operations are grouped into tasks and tasks assigned to roles, but I see no reason why this is any different from what I describe above, it just changes the names of the level of indirection – thanks – appreciate the Post!

  • Alex Kesler

    Thank you for posting your code online. This saved me from having to dig through MSDN documentation to work on accomplishing the same task.