¿Hay alguna manera de que pueda configurar [Authorize (Roles = "admin")] para cada acción en un controlador MVC?

Tengo lo siguiente:

[Authorize(Roles = "admin")]

I am setting it for every action on my controller. However is there some way I can do this globally for the controller?

preguntado el 08 de noviembre de 11 a las 12:11

3 Respuestas

[Authorize(Roles = "admin")]
public class AdminController : Controller
{
}

The attribute works on controllers too.

You can even create a base controller and set the 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)
    {
    }
}

Noticias

First question: You can put [HandleError] in your base controller to get MVC's error handling in all controllers. I've just written a Entrada de blog describiéndolo

Second question: Yes. Put the most specific [Authorize] attribute on the actions. (for instance authorize "users" in the base controller and "admins" on the Edit action).

respondido 08 nov., 11:17

I personally prefer having a base controller for this kind of stuffs. +1 - BigMike

What other things do you put in the base controller? Just wondering if I am missing out on a chance to make things even simpler. - Samantha JT Star

Another related question. Let's say I do this at the controller class level. Then what about if I want to allow two roles such as "user" and "admin" to both access the same action. Can I override at the action level and how would I do that? - Samantha JT Star

If you mark a controller with the attribute, all action methods in the controller are restricted.

respondido 08 nov., 11:16

Yes, all you have to do is put that attribute at the top of the class where you makes it's declaration.

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

When you do this, then every action on this controller will be checked for the admin role.

respondido 08 nov., 11:16

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.