kdawg
kdawg

Reputation: 2009

Possible to [Authorize] at the Area level in ASP.NET MVC 2?

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?

Upvotes: 3

Views: 1477

Answers (2)

Brian Rice
Brian Rice

Reputation: 3257

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;
    }
}

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039160

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

Upvotes: 7

Related Questions