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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top