Does anyone know if there is a way of using a value in Web.Config AppSettings section on an Authorize attribute for a controller in MVC3?
I am currently using something like this in web.config:
<add key="AdminRole" value="Admins"/>
, and then I tried pulling the into class and using the value on the Authorize attribute but .NET complains about the values not being constants, etc.
I just want to be able to use a value set in web.config to filter Authorization so that different deployments can use variations of role names based on their system configurations.
Any help would be appreciated, Thanks!
Here's a working example:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeByConfig : AuthorizeAttribute
{
/// <summary>
/// Web.config appSetting key to get comma-delimited roles from
/// </summary>
public string RolesAppSettingKey { get; set; }
/// <summary>
/// Web.config appSetting key to get comma-delimited users from
/// </summary>
public string UsersAppSettingKey { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!String.IsNullOrEmpty(RolesAppSettingKey))
{
string roles = ConfigurationManager.AppSettings[RolesAppSettingKey];
if (!String.IsNullOrEmpty(roles))
{
this.Roles = roles;
}
}
if (!String.IsNullOrEmpty(UsersAppSettingKey))
{
string users = ConfigurationManager.AppSettings[UsersAppSettingKey];
if (!String.IsNullOrEmpty(users))
{
this.Users = users;
}
}
return base.AuthorizeCore(httpContext);
}
}
And decorate your controller class or method like so:
[AuthorizeByConfig(RolesAppSettingKey = "Authorize.Roles", UsersAppSettingKey = "Authorize.Users")]
Where Authorize.Roles and Authorize.Users are web.config appSettings.
You would have to write your own AuthorizationAttribute class which at runtime reads the value from web.config. In .NET it is not possible to declare an attribute using runtime-dependent values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With