Reusing MVC role authority to display menu items

I am looking to reuse my currently defined Controller / Action Authorize attributes, which define user access roles for displaying menu items (so that the user only sees the menu items that they have access to).

Currently, the display of menu items and the role of the authorization / action attribute is authorized, so any changes will require updating in two places, which may be subject to errors in the future.

I have been studying user authorization attributes, and this is what I still have:

public class MyAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { return false; } var routeData = httpContext.Request.RequestContext.RouteData; string currentAction = routeData.GetRequiredString("action"); string currentController = routeData.GetRequiredString("controller"); var currentUserRoles = GetCurrentUserRoles(); // from the list of menu items, find the menu item with the current action // and controller and check the current user roles entitle access } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary( new { controller = "Error", action = "Unauthorised" }) ); } } 

MenuItems essentially consist of user roles available for a menu item, a text label for the external interface, and the controller URL and action. MenuItems are displayed in a partial view, depending on whether the current user is in the required role to display the MenuItem.

From what I see, I may need an exhaustive list of all controller actions and related user roles that will be reused in both areas, is there a more elegant way to achieve this?

+6
source share
2 answers

After further research, I came across the AuthorizedActionLink nuget package. In essence, this is an ActionLink-based Html Helper that will only show links if the user has access to the action of the target controller (see https://authorizedactionlink.codeplex.com/ ).

So, instead of using @Html.ActionLink() I just use @Html.AuthorizedActionLink() , and the menu is created from user privileges specified at the controller / action level :).

There is also @Html.ActionIsAccessibleToUser(actionName, controllerName) , so the markup surrounding the links, such as <li> , may be omitted.

+3
source

The best way would be to put the authorization logic in a separate class and use it in different places, for example. CustomAuthorize, limiting menu items. Thus, no violation of DRY.

0
source

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


All Articles