For the second time recently, I’m working on an ASP.NET website that uses windows authentication, and gets roles from Active Directory (AD) using WindowsTokenRoleProvider. The roles correspond to the AD groups that the logged-in user is a member of.
I don’t have permission to modify AD group membership, so how do I test my application’s role and permission code? Do I ask our IT guy to swap me in and out of groups while I’m testing?
Yeah, that’s not going to happen.
My solution to this problem is to use a different provider for the roles; the role provider and the membership provider don’t need to be a matched pair. So I can continue to use windows authentication to verify membership (all domain logins are associated with the application, by default.) But I get roles from an XML file, making them easy to change.
How to set it up:
Microsoft has a description of role providers with an example, the ReadOnlyXmlRoleProvider, which is perfect for our purposes. That sample was for IIS6. If you’re using IIS7 on Vista or Windows 7, the provider must be in the Global Assembly Cache. You can find detailed instructions for creating and registering the provider for IIS7 here. We only need the role provider, but the membership provider might be useful in other scenarios. Be careful about that PublicKeyToken when adding the provider to web.config.
Once the provider is installed and configured, just add the desired windows accounts to Users.xml, in the App_Data folder.
<Password>boo</Password> <!-- doesn't matter what's here -->
Now we can access roles in the usual way, without having to bug IT…
string userRoles = ((RolePrincipal)User).GetRoles();
bool inRole = User.IsInRole(SomeRole);
In production, I just change the web.config to use WindowsTokenRoleProvider rather than my ReadOnlyXmlRoleProvider; no recompiling is necessary.