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.
Ok found a solution. After digging around the MvcSiteMap which I know does security trimming, I found this article about it:
http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx
I used a bit of this code, modified slightly, to create the method that gives me the desired result: