Question

I am beginning to decorate my controller classes with

[Authorize(Roles = @"DOMAIN\ADGroup")]

What would be the best method to change that explicit string to a parameter that collects the role assignment from a database, thus allowing flexibility in role assignment that an Admin area can sit on top off.

For example say I have three roles, for arguments sake

  • ReadOnly
  • ReadandWrite
  • Admin

And I want to map those roles to Multiple AD groups

For example

  • ReadOnly --> DOMAIN\Group1, DOMAIN\Group2, DOMAIN\Group3
  • ReadandWrite--> DOMAIN\GroupWrite, DOMAIN\GroupManagers
  • Admin --> DOMAIN\DomainAdmins

This will be editable, I can modify the mapping from role to any AD group I choose in the Admin area of my application.

How can my Authorize attributes take advantage of this?

Was it helpful?

Solution

You can extend the AuthorizeAttribute class. I did it like the following:

public class ExtendedAuthorizeAttribute : AuthorizeAttribute
{
    protected string permission;
    protected string group;

    public ExtendedAuthorizeAttribute(string Permission, string Group)
    {
        permission = Permission;
        group = Group;
    }

    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        var can = PermissionManager.Can(httpContext.User, permission, group);
        if(can.HasValue)
            return can.Value;
        return base.AuthorizeCore(httpContext);
    }
}

OTHER TIPS

Make your own role provider that returns a list of your ReadOnly etc roles based on the current user's AD roles. Then you can use the Authorize attribute to refer to those roles instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top