Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 223
horgh Avatar asked Oct 25 '12 06:10

horgh


2 Answers

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()
{
}
like image 176
Rob Angelier Avatar answered Sep 21 '22 18:09

Rob Angelier


Role with space work fine when I did:

public static class AppRoles
{
    public const string Manager     =@"domain\App Manager";
    public const string Admin       =@"domain\App Admin";
}

[Authorize(Roles = AppRoles.Admin)] 
public class MyAbcController : Controller
{
    //code
}
like image 23
Moji Avatar answered Sep 18 '22 18:09

Moji