Max
Max

Reputation: 5063

In MVC3 how to restrict access to an Area with a role-based authorization?

In MVC3 we can restrict access to a Controller using the [Authorize] attribute, specifying that the user must be in the Administrator role to access any controller action in the class, like in the following example...

[Authorize(Roles = "Administrator")]
public class MyDefaultController : Controller
{
    // Controller code here
}

However how to restrict acces to an entire Area in MVC3 without specify the [Authorize] attribute for each Controller class inside the Area?

Upvotes: 1

Views: 1266

Answers (1)

Behnam Esmaili
Behnam Esmaili

Reputation: 5967

you can use RouteConstraints for doing this :

write a class like this :

       public class AreaRouteConstraint : IRouteConstraint
        {
            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                return  Validate(values["area"];


            }
       }

implementing Validate method is up to you.

and use it like this:

 routes.MapRoute(
name: "yourRouteName",
url: "Url",
defaults: new { controller = "controller", action = "action" , area="area" },
constraints: new AreaRouteConstraint ()
);

Upvotes: 2

Related Questions