Authorize controller or action for domain

A user on StackOverflow asked if it was possible to allow all users from a domain to access a controller or action in MVC. Yes, it is possible. The immediate answer is to apply the AuthorizeAttribute to the controller or action and specify that the roles fall within “MYDOMAIN\Domain Users”. e.g.

  1. [AuthorizeAttribute(Roles = @”DOMAIN\Domain Users")]

Though this is effective, it still isn’t as clean as I would like. So, I have written a simple extension to the AuthorizeAttribute making it more concise. The extension should be placed within your project, and will allow you to decorate the controller in the same fashion, but make it more legible (at least I think) what your intent is. Anyways, here’s the class:

  1. /// <summary>
  2. /// Specified which domains a user should belong to in order to access the decorated
  3. /// controller/action
  4. /// </summary>
  5. public class DomainAuthorizeAttribute : AuthorizeAttribute
  6. {
  7.     private String[] domains = new String[0];
  8.  
  9.     /// <summary>
  10.     /// List of acceptable domains
  11.     /// </summary>
  12.     public String[] Domains
  13.     {
  14.         get { return this.domains; }
  15.         set { this.domains = value; }
  16.     }
  17.  
  18.     protected override bool AuthorizeCore(HttpContextBase httpContext)
  19.     {
  20.         if (httpContext == null)
  21.         {
  22.             throw new ArgumentNullException("httpContext");
  23.         }
  24.  
  25.         // User not logged in
  26.         if (!httpContext.User.Identity.IsAuthenticated)
  27.         {
  28.             return false;
  29.         }
  30.  
  31.         // No roles to check against
  32.         if (this.Domains.Length == 0)
  33.         {
  34.             return true;
  35.         }
  36.  
  37.         // check if they're on any of the domains specified
  38.         String[] roles = this.Domains.Select(d => String.Format(@”{0}\Domain Users", d)).ToArray();
  39.         if (roles.Any(httpContext.User.IsInRole))
  40.         {
  41.             return true;
  42.         }
  43.  
  44.         return false;
  45.     }
  46. }

Now you can decorate your controller like so:

  1. [DomainAuthorize(Domains = new[]{ "DOMAIN1", "DOMAIN2" })]

A little cleaner I think.

Flattr this!