Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Opposite of [Authorise]

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.

like image 849
ajbeaven Avatar asked Sep 04 '09 00:09

ajbeaven


People also ask

Which attribute is used to override required authentication?

. net - Override Authorize Attribute in ASP.NET MVC - Stack Overflow.

What is MVC Authorize?

In MVC, the 'Authorize' attribute handles both authentication and authorization. In general, it works well, with the help of extension to handle AJAX calls elegantly, and to distinguish between unauthorized users and those who are not logged in.

What is AllowAnonymous in MVC?

The AllowAnonymous attribute in MVC is used to skip the authorization which is enforced by Authorization Filter in MVC. [AllowAnonymous] public ActionResult NonSecured() { return View();

What is AllowAnonymous?

AllowAnonymous lets users who have not been authenticated access the action or controller. In short, it knows based on the token it receives from the client.


1 Answers

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.

like image 194
ajbeaven Avatar answered Oct 25 '22 11:10

ajbeaven