Samantha J T Star
Samantha J T Star

Reputation: 32828

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

I have the following:

[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?

Upvotes: 4

Views: 351

Answers (3)

jgauffin
jgauffin

Reputation: 101166

[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)
    {
    }
}

Update

First question: You can put [HandleError] in your base controller to get MVC's error handling in all controllers. I've just written a blog entry describing it.

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).

Upvotes: 5

ptfaulkner
ptfaulkner

Reputation: 712

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.

Upvotes: 1

Arseny
Arseny

Reputation: 7361

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

Upvotes: 1

Related Questions