开发者

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

开发者 https://www.devze.com 2023-01-13 01:08 出处:网络
Slapping on [Authorize] attributes on Controllers and Actions to restrict access is awesome. Is it possible to do the 开发者_如何学Pythonequivalent for an entire Area in MVC 2?Where I can restrict Ar

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

Is it possible to do the 开发者_如何学Pythonequivalent 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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消