0

When i create a custom AuthorizeAttribute to get my roles from a web.config file, users are authorized when the role does not exist.

I added a non-existing role like this:

[AuthorizeDynamic("ddd")]

How can i prevent users from being authorized when a role is not in the web.config file?

The AuthorizeAttribute

public class AuthorizeDynamicAttribute : AuthorizeAttribute
{

    public AuthorizeDynamicAttribute(params string[] RoleKeys)
    {
        List<string> Roles = new List<string>(RoleKeys.Length);

        var AllRoles = (NameValueCollection)ConfigurationManager.GetSection("Roles");
        foreach (var Key in RoleKeys)
        {
            Roles.Add(AllRoles[Key]);
        }

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

The web.config file

<Roles>
  <add key="Administrator" value="Domain\Administrators" />
  <add key="Employee" value="Domain\IIS_IUSRS" />
</Roles>
Rick
  • 9
  • 4
  • You need to override the AuthorizeCore method of AuthorizeAttribute base class, just return false if the role is not in the list of roles listed in config file. You can check this [SO question](http://stackoverflow.com/questions/746998/override-authorize-attribute-in-asp-net-mvc) – Bon Macalindong Nov 09 '15 at 04:22

1 Answers1

0

I fixed it like this, with a custom configuration attribute. I you require the configuration attributes users have to configure the roles you want to authorize in the web.config.

    public AuthorizeFromConfigAttribute(string Role)
    {
        var RolesFromConfig = (PlRoleConfiguration)ConfigurationManager.GetSection("PlRoles");
        foreach (PlRoleElement Element in RolesFromConfig.Elements)
        {
            Role = Role.Replace(Element.Name, Element.Group);
        }

        this.Roles = Role;
    }
Rick
  • 9
  • 4