View Permissions in ASP MVC

I understand that you can use forms authentication to grant / deny access to certain pages based on the criteria of your choice.

However, I would like to stop a little more specifically and say that for users at different resolutions there are different buttons.

I know I can do something like

if(((User)ViewData["CurrentUser"]).IsEmployee)..... 

But it does not seem very elegant and can be very messy.

Are there any recommendations / tools / frameworks that can help me here?

+4
source share
3 answers

Use role-based authentication, and then set the roles accordingly. Then you can do things like:

 if (ViewContext.HttpContext.User.IsInRole("vEmployee") { 

The advantage of this is that it has the basic functionality of ASP.NET - not even for MVC, so it will work with all possible membership providers.

Then you can add redundant view overloading for any control that 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 name it:

 <%= Html.TextBox("name", "value", "vEmployee", null) %> 
+6
source

I had the same issue for a WPF application. It can also work for ASP.NET.

For each "button" (UserControl in WPF), you set the attribute to the role necessary to perform its functions.

At the beginning of your action, you create a list of all the “buttons” for which special permission is required.

Before calling return View (), you call functions that iterate through all the special “buttons” and set visibility based on the user's role.

For WPF, which works because you cannot call the method for get / post ... For the Internet you have to do something more complex, not just hide / show the button ...

I hope this gives you at least a clue ... It was very good for my implementation, but it was just a prototype ... But I think I will use it in the future.

PS: Sample code can be found here.

+1
source

Do not do this. Use a controller for this logic.

-1
source

All Articles