Search code examples
c#asp.netasp.net-mvc-3authorization

Can't make AuthorizeAttribute work, if role name contains spaces


While working over a windows domain intranet site (with <authentication mode="Windows" />) I came across the following problem:

[Authorize(Roles = "Domain Users, Domain Admins")]
public class MyController: Controller {...}

This controller is not available for any user because of the spaces in the names of the active directory groups. So can I make MVC (or ASP.Net) authorize correctly, while using role names (here: names of AD groups) with spaces?

Just similar questions with no respond:

  1. AD Groups with spaces used for roles authorization.
  2. How to write AuthorizeAttribute if a role contains space

Solution

  • Create your own attribute and derive from AuthorizeAttribute. Then override the AuthorizeCore method and implement your own logic with validation on a role that contains a space.

    An example could be something like this:

    public class CustomAuthAttribute : AuthorizeAttribute
    {
       private readonly IUserRoleService _userRoleService;
       private string[] _allowedRoles;
    
       public CustomAuthAttribute(params string[] roles)
       {
          _userRoleService = new UserRoleService();
          _allowedRoles = roles;
       }
       protected override bool AuthorizeCore(HttpContextBase httpContext)
       {
        //something like this.
        var userName = httpContext.User.Identity.Name;
        var userRoles = _userRoleService .GetUserRoles(userName); // return list of strings
        return _allowedRoles.Any(x => userRoles.Contains(x));
       }
    

    }

    Usage

    [CustomAuth("role withspace","admin")]
    public ActionResult Index()
    {
    }