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:
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()
{
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With