Question

Currently my controller looks like this:

public class ProductBrandsController : Controller

I've read online that I can apply the [Authorize] decorator to each Action, but also to the entire Controller itself.

Is there some way to declare a custom decorator so I would call it like so:

[Authorize(Roles = "God")]
public class ProductBrandsController : Controller

Or maybe that's too cumborsome. I wouldn't mind creating a new decorator and calling it like so:

[Administrator]
public class ProductBrandsController : Controller

//Or 

[ContentManager]
public class ProductBrandsController : Controller

Then I would create a custom class to verify if the user that's logged in is in the role.

Any suggestions on how to approach this?

Was it helpful?

Solution

Sure, you just need to derive from the ActionFilterAttribute.

 public class AdministratorRequiredAttribute : ActionFilterAttribute
 {
      override OnActionExecuting() { }
      override OnActionExecuted() { }
      override OnResultExecuting() { }
      override OnResultExecuted() { }
 }

You can override the OnActionExecuting method to insert logic to check your user's authentication; when it is not sufficient, you can redirect the user out of the action method with the context object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top