Poda de interfaz de usuario de MVC basada en el atributo Autorizar controlador / acción

I have an secure application with an Authorize attribute on each action.

[Authorize(Roles = "Role1,Role2")]
public ActionResult MyAction(int id)
    return View();

In my UI, I have links to these controller/actions. I would like to create a custom HtmlHelper for the links that accepts controller and action names:

@Html.SecuredLink("Click Me", "MyAction", "MyController");

And this would determine weather to render itself or not based on if the user has permission to the given action:

public static MvcHtmlString SecuredLink(this HtmlHelper helper, string text, string action, string controller)
    var userId = Membership.GetUserId();

    var userHasRightsToThisAction = IsActionAccessibleToUser(helper.ViewContext.RequestContext.HttpContext, controller, action); // <- How would this work?

    if (userHasRightsToThisAction )
       // Render Link
       // ...

I have been unable to find a way to easily test the action from code for authorization status.

preguntado el 08 de noviembre de 11 a las 14:11

Can you clarify why is not possible to render the link normally and then redirect in a custom AuthorizeAttribute ? However I think you should look into the User.Identity object first, having the Authorization name, you can then decide on rendering. -

I don't want users to be able to click the link if they do not have rights to the page it leads to. -

2 Respuestas

Ok found a solution. After digging around the MvcSiteMap which I know does security trimming, I found this article about it:


I used a bit of this code, modified slightly, to create the method that gives me the desired result:

    /// <summary>
    /// Determine if a controller/action is accessible for a user
    /// </summary>
    /// <param name="context">Current HttpContext</param>
    /// <param name="controllerName">Target controller</param>
    /// <param name="actionName">Target action</param>
    /// <returns>True/false if the action is accessible</returns>
    public static bool IsActionAccessibleToUser(HttpContextBase context, string controllerName, string actionName)
        // Find current handler
        MvcHandler handler = context.Handler as MvcHandler;

        if (handler != null)
            // try to figure out the controller class
            IController controller = null;
                controller = ControllerBuilder.Current.GetControllerFactory().CreateController(handler.RequestContext, controllerName);                    
            catch (System.Web.HttpException e)
                throw new Exception("The controller '" + controllerName + "Controller' was not found.", e);

            // Find all AuthorizeAttributes on the controller class and action method
            object[] controllerAttributes = controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true);
            object[] actionAttributes = controller.GetType().GetMethod(actionName).GetCustomAttributes(typeof(AuthorizeAttribute), true);

            // No attributes, then the action is open to all
            if (controllerAttributes.Length == 0 && actionAttributes.Length == 0) return true;

            // Find out current principal
            IPrincipal principal = handler.RequestContext.HttpContext.User;

            // Do we pass the roles for the controller?
            string roles = "";
            if (controllerAttributes.Length > 0)
                AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
                roles = attribute.Roles;

                if (!PassRoleValidation(principal, roles)) return false;

            // Do we pass the roles for the action?
            if (actionAttributes.Length > 0)
                AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
                roles = attribute.Roles;

                if (!PassRoleValidation(principal, roles)) return false;

            return true;

        return false;

    private static bool PassRoleValidation(IPrincipal principal, string roles)
        // no roles, then all we need to be is authenticated
        if (string.IsNullOrEmpty(roles) && principal.Identity.IsAuthenticated) return true;

        string[] roleArray = roles.Split(',');

        // if role contains "*", it's open to all
        if (roleArray.Any(role => role == "*")) return true;

        // Determine if the current user is allowed to access the current node
        if (roleArray.Any(principal.IsInRole)) return true;

        return false;

respondido 10 nov., 11:01

This is not going to work if your controller has two actions with the same name (e.g one for POST and one for GET requests). controller.GetType().GetMethod(actionName) arrojará AmbiguousMatchException. - Maksim Vi.

Ok, quick and dirt solution:

prepare a function for building the Urls server side

something like this will probably be the best choice:

public static string GetUrl(string Action, string Controller, object RouteValues) {
    UrlHelper Url = new UrlHelper(HttpContext.Current.Request.RequestContext);
    return Url.Action(Action, Controller, RouteValues);

In your helper, obtain User Authentication infos and return the built url or string.Empty.

public static string SecureLink(this HtmlHelper helper, string Action, string Controller, object RouteValues)
  YourUserObject LoggedUser = /* Whatever you need to obtain your UserId */
  if (LoggedUser.IsSuperUser) {
    return GetUrl(Action, Controller, RouteValues);
  return string.empty;

If your result is HTML Encoded just use MvcHtmlString in place of string as a return value. Otherwise beware, you may need to use @Html.Raw for emitting it.

PS: obviously I've not added full <a href .../> generation in this sample code, is up to you decide which parameters are need (add them to the Helper signature), I usually copy the signatures of other @Html helpers (so Name, Value and a list of HtmlAttributes).

respondido 09 nov., 11:13

Where you say "LoggedUser.IsSuperUser", I want to determine the rights based on the Authorize decortations on each MVC Action. This is the part I am struggling with. So if the Action has "Authorize(Roles = "Associate"), I want to determine this somehow and have the system tell me if the current user is an "Associate", or better yet, do they just qualify to execute the Action. - CodeGrue

I sincerely doubt you can access Attributes properties from an Helper, the Helper is executed for rendering the View, after the Action has been executed. You can try to build a javascript (client side) artifact to enable/disable Links, but that will make the Attributes decoration useless. IMHO In this case is better to let the link clickable and handle the NotAuthorized server side. - BigMike

Well, I am testing a controller/action from a different one, not the same. So I am on A/B and the link goes to A/C, so I want to ask A/C if the user has rights to go there. So I am not trying to test the controller/action I am on from within it. - CodeGrue

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.