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:
- 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")]
.
- 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?
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.
Please have a look at this excellent example, in which author talks about the problem you are facing.
http://www.ryanmwright.com/2010/04/25/dynamic-controlleraction-authorization-in-asp-net-mvc/