Thursday, February 14, 2013

Get Authorized Roles from Web.Config

Introduction
To avoid hard coding the names of AD Groups, it is best to just pull them from a place where they already exist. They usually exist in the Authorization section of your web.config: configuration\system.web\authorization
So I started looking up how to do this and to my surpise it was more difficuilt than it had to be as usual when it comes to any xml file. Some solutions online just say to read in your web.config as an XmlDocument and I always think that is a last resort. If there is an API for it, use the API - don't reinvent the wheel as it is confusing for anyone that has to read your code later and you just wasted time rewriting something that existed already.

How to get the Authorization Roles from the Web.config
I don't have much to explain about this process other than it was hard to figure out, but now that is finished I don't want to have to think about it again. The code pretty much explains it all. Unfortunately the AuthorizationRuleCollection does not support any Linq operations, so this was uglier than I would have liked it to be. I am using a loop which I am not fond of, but I couldn't figure out a safer way to do this. The only good news is usually there are only a hand full of rules to loop through.

//Import the following
using System.Configuration;

//Get the web.config configuration for THIS web.config (hence the ~)
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

//Get the Authorization section which has the allowed roles in it (AD Groups)
AuthorizationSection auth = (AuthorizationSection)config.GetSection("system.web/authorization");

string[] arrRoles = new string[0];

//TODO: Find a better way to query the rules
//Loop through each rule
foreach(AuthorizationRule obj in auth.Rules)
{
 //Find the Allow Rule
 if (obj.Action == AuthorizationRuleAction.Allow)
 {
  //Resize the array
  arrRoles = new string[obj.Roles.Count];

  //Copy the roles from the StringCollection to an array of string
  obj.Roles.CopyTo(arrRoles, 0);

  //Exit loop after found
  break;
 }
}

Resources
http://stackoverflow.com/questions/213784/in-my-codebehind-class-how-do-i-retrieve-the-authorized-roles
http://msdn.microsoft.com/en-us/library/system.collections.specialized.stringcollection.copyto.aspx

No comments:

Post a Comment