Yann Trevin
Yann Trevin

Reputation: 3823

How to avoid duplication of authorization code logic

I've written a custom authorization attribute derived from System.Web.Mvc.AuthorizeAttribute. I'm using it successfully from my controllers to restrict the access to certain features.

public class ArticleController : Controller
{
    [CustomAuthorize(Role.Administrator)]
    public ActionResult Delete(int id)
    {
       // ...
    }
}

And that works fine. Now I want to show or hide HTML elements according to the same authorization logic. For example, in my view "Article", I want to hide the action button "Delete" if the user is not a administrator. I've written something like that:

<ul id="menu">
   <li>@if (User.IsInRole(Role.Administrator)) { 
          @Html.ActionLink("Delete", "Delete", "Article", new { id = article.ID }, null)
       } </li>
</ul>

It works fine as well, but it creates code logic duplication because I need to specify twice the necessary credientials to perform an action:

What is the best way to avoid this duplication? Is there any way to reuse my custom authorization attribute from views?

Upvotes: 5

Views: 549

Answers (3)

goenning
goenning

Reputation: 6654

A custom helper should be the best option, something like:

@Html.SecureActionLink("Delete", "Delete", "Article")

This helper would check on some kind of service to see if the current user/role has permission on this link.

Upvotes: 3

driushkin
driushkin

Reputation: 3659

I would create custom html helper for this.

public MvcHtmlString AuthorizedActionLink(this HtmlHelper htmlHelper, 
string actionName, ... , Role role)

And if you feel the Role parameter is redundant, you may inspect the controller action using Reflection and determine allowed roles automatically.

Upvotes: 1

erikkallen
erikkallen

Reputation: 34411

Make the menu a partial view .

Upvotes: 1

Related Questions