Specifying Roles in web.config of an asp.net MVC application

James picture James · Jul 18, 2012 · Viewed 16.2k times · Source

I am creating an MVC application with forms auth. I am authenticating against active directory and so have created a custom RoleProvider. My application is only concerned with a small set of roles which up until now I have been defining in the appSettings section of my web.config:

<appSettings>
  <add key="DirectorRole" value="Domain\Directors" />
  <add key="ManagementRole" value="Domain\Managers" />
  ...
</appSettings>

However I have run into a couple of problems with this approach:

  1. I cannot reference these setting in my contoller data annotations: [Authorize(Roles = ConfigurationManager.AppSettings["DirectorRole"])] as it wont compile so I have to specify the name of the group again: [Authorize(Roles = "Domain\\Directors")].
  2. In my web.config, I would like to specify the groupsToUse for my role provider and just reference a pre-existing list, rather than maintain two seperate lists of the same set of roles.

It seems that there must be a better/reusable way to define the roles in the web.config, can someone point me in the right direction please?

Answer

Mohayemin picture Mohayemin · Jul 18, 2012

I would prefer using a custom authorize attribute. Like this one.

public class MyAuthorizeAttribute : AuthorizeAttribute {

    public MyAuthorizeAttribute(params string[] roleKeys) {
        List<string> roles = new List<string>(roleKeys.Length);

        //foreach(var roleKey in roleKeys) {
            //roles.Add(ConfigurationManager.AppSettings["DirectorRole"]);
        //}
        var allRoles = (NameValueCollection)ConfigurationManager.GetSection("roles");
        foreach(var roleKey in roleKeys) {
            roles.Add(allRoles[roleKey]);
        }

        this.Roles = string.Join(",", roles);
    }
}

In your controller, use:

[MyAuthorize("DirectorRole")]

In your web.config

  <configSections>
    <section
      name="roles"
      type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <roles>
    <add key="DirectorRole" value="Domain\Directors" />
    <add key="ManagementRole" value="Domain\Managers" />
  </roles>

I hope this will solve your first problem just fine. And twiking a little will solve the second one too.