/// <summary>
/// <example>
/// public class SecuredController : Controller
// {
// [AuthorizeFromConfiguration(AppSettingRolesKey = "Roles")]
// in config file add: <add key="Authorization.Roles" value="Role1,Role2"/>
// public ActionResult Index()
// {
// return View();
// }
// [AuthorizeFromConfiguration(AppSettingUsersKey = "Users")]
// in config file add: <add key="Authorization.Users" value="domain\user1,domain\user2"/>
// public ActionResult Index()
// {
// return View();
// }
// }
//</example>
/// </summary>
public class AuthorizeFromConfigurationAttribute : AuthorizeAttribute
{
public const string ConfigurationKeyPrefix = "Authorization.";
private string _appSettingRoleKey;
private string _appSettingUsersKey;
public string AppSettingRolesKey
{
get { return _appSettingRoleKey; }
set
{
if (!string.IsNullOrWhiteSpace(value))
{
_appSettingRoleKey = value;
string roles = GetAppSettingValue(_appSettingRoleKey);
if (!string.IsNullOrWhiteSpace(roles))
Roles = roles;
}
}
}
private static string GetAppSettingValue(string key)
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentNullException("key");
}
if (key.IndexOf(ConfigurationKeyPrefix,StringComparison.OrdinalIgnoreCase) < 0)
{
key = string.Format("{0}{1}", ConfigurationKeyPrefix, key);
}
string keyValue = string.Empty;
if (ConfigurationManager.AppSettings.AllKeys.Contains(key))
{
keyValue = ConfigurationManager.AppSettings[key];
}
else
{
throw new Exception(string.Format("The key \"{0}\" has not been defined in the configuration file", key));
}
return keyValue;
}
public string AppSettingUsersKey
{
get { return _appSettingUsersKey; }
set
{
if (!string.IsNullOrWhiteSpace(value))
{
_appSettingUsersKey = value;
string users = GetAppSettingValue(_appSettingUsersKey);
if (!string.IsNullOrWhiteSpace(users))
Users = users;
}
}
}
}