10
@if (Roles.IsUserInRole("Administrators"))
{
  <li>@Html.ActionLink("Create New", "Create")</li>
}

I have bounch of roles for users and many actions is accesible for more than one role.

It will be very hard to change that if statement in many places - is where a way to hide actionlink based only on Athorize(Roles="Administrator, SomethingElse")?

Maybe there is a way to write custom helper that checks user premisions and using it instead of Html.Actionlink?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
SpoksST
  • 776
  • 1
  • 8
  • 24
  • Maybe this could be answer to your question: http://stackoverflow.com/questions/5477019/how-to-override-the-actionlink-behavior/5477092#5477092 – Tx3 Nov 19 '11 at 22:03
  • It should work, however I cannot force it to work on mvc 3 – SpoksST Nov 19 '11 at 23:15

2 Answers2

8

After some trial and error, the solution suggested here works. However sugested solution was for previous framework version.

Edited solution:

 public static class AuthorizeActionLinkExtention
{
    public static MvcHtmlString AuthorizeActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
    {
        if (HasActionPermission(helper, actionName, controllerName))
            return helper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);

        return MvcHtmlString.Empty;
    }
    public static MvcHtmlString AuthorizeActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName)
    {
        if (HasActionPermission(helper, actionName, controllerName))
            return helper.ActionLink(linkText, actionName, controllerName);

        return MvcHtmlString.Empty;
    }
    public static MvcHtmlString AuthorizeActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
    {
        if (HasActionPermission(helper, actionName, controllerName))

            return helper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);

        return MvcHtmlString.Empty;
    }
    static bool HasActionPermission(this HtmlHelper htmlHelper, string actionName, string controllerName)
    {
        ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName)
            ? htmlHelper.ViewContext.Controller
            : GetControllerByName(htmlHelper, controllerName);

        ControllerContext controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerToLinkTo);

        ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType());
        ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

        return ActionIsAuthorized(controllerContext, actionDescriptor);
    }

    static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (actionDescriptor == null)
            return false;

        AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);
         foreach (Filter authFilter in FilterProviders.Providers.GetFilters(authContext, actionDescriptor))
        {
            if (authFilter.Instance is System.Web.Mvc.AuthorizeAttribute)
            { 


            ((IAuthorizationFilter)authFilter.Instance).OnAuthorization(authContext);

            if (authContext.Result != null)
                return false;
            }
        }

        return true;
    }

    static ControllerBase GetControllerByName(HtmlHelper helper, string controllerName)
    {
        IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();

        IController controller = factory.CreateController(helper.ViewContext.RequestContext, controllerName);

        if (controller == null)
        {
            throw new InvalidOperationException(
                string.Format(
                    CultureInfo.CurrentUICulture,
                    "Controller factory {0} controller {1} returned null",
                    factory.GetType(),
                    controllerName));
        }

        return (ControllerBase)controller;
    }

}
Community
  • 1
  • 1
SpoksST
  • 776
  • 1
  • 8
  • 24
7

I would write a custom action link helper:

public static class LinkExtensions
{
    public static IHtmlString ActionLinkIfInRole(
        this HtmlHelper htmlHelper, 
        string roles,
        string linkText, 
        string action
    )
    {
        if (!Roles.IsUserInRole(roles))
        {
            return MvcHtmlString.Empty;
        }
        return htmlHelper.ActionLink(linkText, action);
    }
}

and then in my views:

@Html.ActionLinkIfInRole("Administrators", "Create New", "Create")
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I think he wants to pass in a arbitrary list of roles. You will need to iterate through the list of roles and check each one for IsUserInRole. Return return htmlHelper.ActionLink(linkText, action); as soon as you hit a roleName that is in role. If you get thru the list, return string.empty – RickAndMSFT Nov 20 '11 at 19:08
  • 1
    This is the same as with if statedment - I need to provide role list. – SpoksST Nov 20 '11 at 21:45