Reputation: 11701
I understand that you can use forms authentication to grant/deny access to certain pages based on the criteria of your choosing.
However I wish to go in a little more specific than that and say, have different buttons appear for users based on thier permissions.
I know I could do something like
if(((User)ViewData["CurrentUser"]).IsEmployee).....
But that doesn't seem very elegant and could get messy very quickly.
Are there any guidelines/tools/framework features that could help me out here?
Upvotes: 4
Views: 3439
Reputation: 126547
Use role-based authentication, then set roles appropriately. Then you can do things like:
if (ViewContext.HttpContext.User.IsInRole("vEmployee") {
The advantage of this is that it's core ASP.NET functionality -- not even MVC-specific -- so it's going to work with every possible membership provider.
Then you can add a view helper overload for whatever control you want to conditionally display:
public static string TextBox(this HtmlHelper helper,
string name, string value, string role, object htmlAttributes)
{
if helper.ViewContext.HttpContext.User.IsInRole(role) {
return helper.TextBox(name, value, htmlAttributes);
}
else
{
return null;
}
}
...and call it:
<%= Html.TextBox("name", "value", "vEmployee", null) %>
Upvotes: 6
Reputation: 2485
I had the same issue a while ago for a WPF application. It could work for ASP.NET as well.
For every "button" (UserControl in WPF) you set by attribute the role needed to execute its functionality.
At the begninning of your Action, you create a list of all the "Buttons" that require a special authorization.
Before calling the "return View()" you call a functions that iterate all you special "Buttons" and sets is visibility based on the role of the user.
For WPF that works because you can't call the method by a get/post request... For the web you should make something more sophisticated not just hide/show the button...
I hope this gives you at least a clue... It worked pretty fine for my implementation, but it was just a prototype...But I think I'll use it in future.
PS: Sample code can be found here
Upvotes: 1