3

Slapping on [Authorize] attributes on Controllers and Actions to restrict access is awesome.

Is it possible to do the equivalent for an entire Area in MVC 2? Where I can restrict Area-wide access dependent on Roles/Users/whatever in a central place instead of littering them throughout all the Controllers?

kdawg
  • 2,019
  • 21
  • 31

2 Answers2

7

You could use a base controller decorated with this attribute that all your controllers in the area derive from.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

For MVC 3 and above:

I just started on this... but so far this is working pretty good for me.

I create a custom AuthorizeAttribute class and add this in the RegisterGlobalFilters function.

In CustomAuthorizeAttribute I check for various conditions based on the area it is in.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CustomAuthorizeAttribute());
        filters.Add(new HandleErrorAttribute());
    }
}

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var routeData = httpContext.Request.RequestContext.RouteData;
        var controller = routeData.GetRequiredString("controller");
        var action = routeData.GetRequiredString("action");
        var area = routeData.DataTokens["area"];
        var user = httpContext.User;
        if (area != null && area.ToString() == "Customer")
        {
            if (!user.Identity.IsAuthenticated)
                return false;
        }
        else if (area != null && area.ToString() == "Admin")
        {
            if (!user.Identity.IsAuthenticated)
                return false;
            if (!user.IsInRole("Admin"))
                return false;
        }
        return true;
    }
}
Brian Rice
  • 3,107
  • 1
  • 35
  • 53