Is it possible to [Authorize] at the district level in ASP.NET MVC 2?

Denying attributes [Authorize]on controllers and actions to restrict access is amazing.

Is it possible to make an equivalent for the whole area in MVC 2? Where can I restrict access within a zone depending on Roles / Users / something in a central place, instead of clogging them in all controllers?

+3
source share
2 answers

You can use the base controller, decorated with this attribute, from which all your controllers in the field are made.

+7
source

For MVC 3 and above:

... .

AuthorizeAttribute RegisterGlobalFilters.

CustomAuthorizeAttribute , .

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

Source: https://habr.com/ru/post/1761790/


All Articles