Geeks With Blogs
Old blog. Blog moved to thomasgathings.com I would delete this...but I don't see the option

 With ASP.Net MVC, you can easily use AuthorizeAttribute to control access to controllers and actions. I found it limiting within the context of Windows Authentication. First, I wanted to configure the roles outside of an attibute. Properties of AuthorizeAttribute, as with all attributes, must be set a design-time, such as [Authorize(Roles = “MyCompany\AppAdmin”)]. I want to break that out to configuration so I can have [Authorize(Roles = “Editor”)] and configure the Editor role like this EditorRole=”MyCompany\AppAdmin”, where MyCompany\AppAdmin is an Active Directory security group.

On a semi-related note, it isn't possible to use Users and Roles together with the AuthorizeAttribute. The implementation of AuthorizeCore (an internal, form template pattern in the AuthorizeAttribute class) is written to assert both users and roles. Crack it open with reflector and it's clearly evident. In the following example, only Joe.User can access this controller. Everyone else, including members of the Admins role, will recieve a 401.

[Authorize(Roles="Admins", Users="MyCompany\\Joe.User")]

The following code achieves my goals: configurable authorization using Roles, Users, or both in context of Windows Authentication.

 

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]

public class AuthorizeByConfigurationAttribute : AuthorizeAttribute

{

    private static string[] SafeSplit(string toSplit)

    {

        if (string.IsNullOrEmpty(toSplit)) return new string[0];

        var splitString = toSplit.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

        return splitString;

 

    }

 

 

    protected override bool AuthorizeCore(HttpContextBase httpContext)

    {

        if (false == string.IsNullOrEmpty(Users))

        {

            throw new NotSupportedException("Use of the Users property is not allowed; match Roles to settings in configuration with convention 'GroupsInRoleOf.<NamedRole>' for groups or 'UsersInRoleOf.<NamedRole>', where <NamedRole> is anything, such as Admin.");

 

        }

 

        string rolesToCheck = ConfigurationManager.AppSettings["GroupsInRoleOf." + Roles];

        string usersToCheck = ConfigurationManager.AppSettings["UsersInRoleOf." + Roles];

 

        if (httpContext == null)

        {

            throw new ArgumentNullException("httpContext");

        }

 

        IPrincipal user = httpContext.User;

 

        if (!user.Identity.IsAuthenticated)

        {

            return false;

        }

 

        if ((SafeSplit(usersToCheck).Length > 0) && SafeSplit(usersToCheck).Contains<string>(user.Identity.Name, StringComparer.OrdinalIgnoreCase))

        {

            return true;

        }

 

        if ((SafeSplit(rolesToCheck).Length > 0) && SafeSplit(rolesToCheck).Any<string>(new Func<string, bool>(user.IsInRole)))

        {

            return true;

        }

 

        return false;

    }

 

 

}

 

 

This first-cut uses concatenated keys in app settings. Better to have a custom ConfigurationSection, a simple class configured with an IOC-container, or the like.

 

Sample appSettings

 

 

<add key="GroupsInRoleOf.Editor" value="MyCompany\MyAppEditors"/>

<add key="UsersInRoleOf.Editor" value="MyCompany\JoeThePresident"/>

Sample attribute

 

[AuthorizeByConfiguration(Roles = "Editor")]

 

Posted on Thursday, June 25, 2009 5:06 PM | Back to top


Comments on this post: Configurable Authorization: Subclassing ASP.Net MVC AuthorizeAttribute

# re: Configurable Authorization: Subclassing ASP.Net MVC AuthorizeAttribute
Requesting Gravatar...
Congrulation.It is very benefical
Left by Barbaros Tombaz on Oct 30, 2009 4:42 PM

# re: Configurable Authorization: Subclassing ASP.Net MVC AuthorizeAttribute
Requesting Gravatar...
Thanks a lot! Nice work :) That's what i've looked for.
Left by Elena on Jul 01, 2010 10:22 AM

# re: Configurable Authorization: Subclassing ASP.Net MVC AuthorizeAttribute
Requesting Gravatar...
Perfect, thanks!
Left by dizzwave on Mar 31, 2011 2:30 PM

# re: Configurable Authorization: Subclassing ASP.Net MVC AuthorizeAttribute
Requesting Gravatar...
Good stuff!

Just what I needed for a quick cut and paste job :)
Left by oli on Jan 31, 2012 2:47 PM

Your comment:
 (will show your gravatar)


Copyright © Thomas Gathings | Powered by: GeeksWithBlogs.net | Join free