Reputation:
Let's say I have a controller action that is restricted to only certain users, like this:
[Authorize(Roles="somerole")]<br />
public ActionResult TestRestricted() {
return View();
}
On a view, that is public to everyone I have a link to the action defined above:
<%= Html.ActionLink("Click here!", "TestRestricted") %>
What I'd like to do is hide the link for everyone that is not allowed perform the "TestRestricted"-action. Is there a way to check if the current user is authorized to use the corresponding action? Without defining any additional or duplicate access rules in addition to the authorization filter?
Upvotes: 3
Views: 2270
Reputation: 16435
There is nothing in the MVC framework that can control permissions at such a granular level.
First Approach
This is by far the easiest approach. The drawback is having to assign the role to each action link.
What you could do, is write a Action HtmlHelper to control the permissions at a link level. Make sure you include the namespace System.Web.Mvc.Html
.
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string role)
{
MvcHtmlString link = new MvcHtmlString(string.Empty);
if (htmlHelper.ViewContext.RequestContext.HttpContext.User.IsInRole(role))
{
link = htmlHelper.ActionLink(linkText, actionName);
}
return link;
}
<%= Html.ActionLink("Click here!", "TestRestricted", "somerole") %>
Second Approach
You could use reflection to discover the action(method) being called. Once discovered a simple check of the attributes would tell you if the authorize attribute was present and what role it was set too.
Upvotes: 2
Reputation: 9192
This may help: http://weblogs.asp.net/rashid/archive/2009/09/06/asp-net-mvc-and-authorization-and-monkey-patching.aspx
I am also trying to find an answer to this question.....
Upvotes: 1