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.
. net - Override Authorize Attribute in ASP.NET MVC - Stack Overflow.
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.
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();
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.
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.
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