Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorize Attribute MVC 3 & Web.Config AppSettings Value

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!

like image 793
M4V3R1CK Avatar asked Dec 17 '22 09:12

M4V3R1CK


2 Answers

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.

like image 90
ScottE Avatar answered Dec 31 '22 04:12

ScottE


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.

like image 42
marcind Avatar answered Dec 31 '22 04:12

marcind