ASP.NET MVC: opposite [Authorize]

The authorization filter allows you to specify a group of users who can access the controller or action:

[Authorize(Roles="Administrator")] public class HomeController : Controller { // code } 

I would like to know if you can instead specify a user group that cannot access the controller or action.

+6
authorization asp.net-mvc
source share
3 answers

I tried to create my own AuthorizationAttribute after the twk suggestion:

 public class Restrict : AuthorizeAttribute { private readonly string _role; public Restrict(string role) { _role = role; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException("httpContext"); if (httpContext.User.IsInRole(_role)) return false; return true; } } 

And I use it as follows:

 [Restrict("Administrator")] public class HomeController : Controller { // code } 

I'm not sure if this is the right practice, but it does the job.

+5
source share

You must prepare your own ActionFilter that can implement such a function. By default, there is a rule to reject everything, but it is allowed by a specific filter for authorization actions (as you already know).

Some inspiration can be found there.

+1
source share

Based on ajbeaven's answer, I managed to extend it to a list of roles instead of a single role.

First, the Restrict class:

 public class Restrict : AuthorizeAttribute { private List<string> _roles; public string Roles { get { string roles = ""; if (_roles != null && _roles.Count > 0) { int counter = 0; foreach (string role in _roles) { counter++; if (counter == _roles.Count) { roles = role; } else { roles += role + ","; } } } return roles; } set { _roles = new List<string>(); string[] roles = value.Split(','); foreach (string role in roles) { _roles.Add(role); } } } public Restrict() { _roles = new List<string>(); } protected override bool AuthorizeCore(HttpContextBase httpContext) { bool result = true; if (httpContext == null) { throw new ArgumentNullException("httpContext"); } foreach (string role in _roles) { if (httpContext.User.IsInRole(role)) { result = false; break; } } return result; } } 

Then add the AppRoles class to make the whole solution reusable:

 public static class AppRoles { public const string Role1 = "Role1"; public const string Role2 = "Role2"; } 

Using:

 [Authorize] [Restrict(Roles = AppRoles.Role1 + "," + AppRoles.Role2)] public ActionResult Index() { return View(); } 
+1
source share

All Articles