views:

189

answers:

3

The authorize filter allows you to specified group of users that can access a controller or action:

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

I would like to know if it is possible to, instead, specify a group of users that cannot access a controller or action.

+1  A: 

You should prepare your own ActionFilter which can implement such a feature. By default there is a rule of deny everything, but allow defined by Authorize action filter (as you already know).

Some inspiration can be found there

twk
A: 

How about using !=

Walrus von Zeppelin
That don't work. At least not in my testing.
griegs
This won't work as the piece of code is assigning a variable, rather than evaluating. C# assignation is =, C# evaluation is ==.
StuperUser
+2  A: 

I tried creating my own AuthorizationAttribute after twk's 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 like this:

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

I'm unsure whether it is correct practice but it does the job.

ajbeaven
looks fine to me! :)
jeef3
Does your Restrict attribute accept more than one role at once?
twk
+1 Nice simple solution
CmdrTallen