Is there a way I can set [Authorize (Roles = "admin")] for every action in the MVC controller

I have the following:

[Authorize(Roles = "admin")] 

I configure it for every action on my controller. However, is there a way to do this globally for the controller?

+4
source share
3 answers
 [Authorize(Roles = "admin")] public class AdminController : Controller { } 

The attribute also works on controllers.

You can even create a base controller and set an attribute on it (and therefore get the same authorization on all derived controllers)

 [Authorize(Roles = "user")] public class BaseController : Controller { } public class NewsController : BaseController { } public class ForumController : BaseController { [HttpPost, Authorize(Roles="admin")] public ActionResult Delete(int id) { } } 

Update

First question: you can put [HandleError] in your base controller to get MVC error handling in all controllers. I just wrote a blog post describing it.

Second question: Yes. Put the most specific [Authorize] attribute on the action. (for example, allow "users" in the base controller and "administrators" in the "Edit" action).

+5
source

If you tag the controller with an attribute, all action methods in the controller are limited.

+1
source

Yes, all you have to do is put this attribute at the top of the class where you make it a declaration.

 [Authorize(Roles = "admin")] public class TheController : Controller 

When you do this, all actions on this controller will be checked for the administrator role.

+1
source

Source: https://habr.com/ru/post/1380179/


All Articles