Role-based security is not a new concept in ASP.NET, It introduced in VS 2005. What is interesting today is one of my friend asking me how he can authorize access to certain part of an ASP.NET application (that runs using Windows Authentication) based on some attributes set in an Active Directory schema.

Normally, when you use Active Directory with ASP.NET, you would use an Active Directory group as a role, and then use the web.config file to specify authorization for the role to your resources. This works if your Active Directory is designed to have AD groups that map straight to the roles of your applications. But chances are that they don’t map 100%. Or there might be other business reasons that such groups cannot be created.

In order to get around the situation, what we can do is to setup authorization the same way: using web.config and set <allow roles="”Role1?"></allow> to authorize access to your resources.

Then we need to override the Application_AuthenticateRequest event of the ASP.NET application. This is implemented via the Global.asax file of the ASP.NET application.

By changing the Application_AuthenticateRequest method, you can insert roles to the principal object the current thread carries.

void Application_AuthenticateRequest(object sender, EventArgs e)
  if (Request.IsAuthenticated())
    // To determine some business rules that what roles to grant to the current user
    string[] roles = {"Role1", "Role2"};
    Thread.CurrentPrincipal = new GenericPrincipal(Context.User.Identity, roles);  // set the Principal of the current thread

So to get back to the example, what my friend can do is to insert logic inside the if block of the code above and determine by the attribute of the Active Directory record of the current user, and assign the proper roles to the GenericPrincipal object. The rest of the authorization will then be handled by ASP.NET using the Role-based security model.