Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC role-based routing

I have a project with 2 areas /Admin and /User.

Admin's default route is /Admin/Home/Index and user's default route is /User/Home/Index.

Is it possible to implement routing to make their home URL to look like /Profile/Index but to show content from /Admin/Home/Index for admins and /User/Home/Index for users?

upd

Finally find out how to do it

context.MapRoute(
    "Admin",
    "Profile/{action}",
    new { area = AreaName, controller = "Home", action = "Index" },
    new { RoleConstraint = new Core.RoleConstraint() },
    new[] { "MvcApplication1.Areas.Admin.Controllers" }
);
...
context.MapRoute(
    "User",
    "Profile/{action}",
    new { area = AreaName, controller = "Home", action = "Index" },
    new { RoleConstraint = new Core.RoleConstraint() },
    new[] { "MvcApplication1.Areas.User.Controllers" }
);

public class RoleConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        string roleName = db.GetRoleByUserName(httpContext.User.Identity.Name);
        string areaName = route.Defaults["area"].ToString();
        return areaName == roleName;
    }
}

It works, but as for me it's not the MVC way. Does anybody knows how to do it right?

like image 856
Dmytro Avatar asked Nov 18 '11 10:11

Dmytro


People also ask

What is role based authentication in MVC?

What is Role Based Authentication In ASP.NET MVC? Role Based Authentication is Membership and Role providers. These providers allows us to define Roles, Users and assign roles to users which helps us to manage Authorization.

What are the three main elements of routing in MVC 3?

The three segments of a default route contain the Controller, Action and Id.


2 Answers

Yes. The example you showed is very close to many of the Microsoft provided samples for using Route Constraints. The routing engine acts as a pre-proxy (or router if you will) before the request is passed into a control. Items like IRouteConstraint are defined so you can do just what you described.

like image 160
detroitpro Avatar answered Oct 14 '22 15:10

detroitpro


I like that solution as it's noted, but one thing to keep in mind is that routing itself shouldn't be used as the sole form of security. Just keep in mind that you should be securing your Controllers and Actions with the [Authorize] attribute, or however you're limiting access.

like image 29
hsrob Avatar answered Oct 14 '22 17:10

hsrob