Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • In the controller to block or allow the action.
  • In the view to show or hide the action link.

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

like image 267
Yann Trevin Avatar asked Feb 23 '11 11:02

Yann Trevin


1 Answers

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.

like image 124
goenning Avatar answered Sep 28 '22 03:09

goenning