Allow users with roles to access controller methods dynamically. I have a typical scenario where I want to allow users to access the pages dynamically as the prvilege set to each roles can be change by a userinterface. I have three actionresult
Controller:
public class HomeController : Controller
{
[CustomAuthorize(Roles="Admin")]
Public Actionresult UI01(){
return View();
}
[CustomAuthorize(Roles="Admin")]
Public Actionresult UI02(){
return View();
}
[CustomAuthorize(Roles="Admin")]
Public Actionresult UI03(){
return View();
}
}
View: I hide the menu items by checking the admin role.
@*menu items*@
@if((Roles.IsUserInRole("Admin")){
<li>@Html.ActionLink("Rating", "UI01", "Home")</li>
}
@if((Roles.IsUserInRole("Admin")){
<li>@Html.ActionLink("Map", "UI02", "Home")</li>
}
@if((Roles.IsUserInRole("Admin")){
<li>@Html.ActionLink("Sales", "UI03", "Home")</li>
}
authorize attribute classs:
public class CustomAuthorize : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Account", action = "Error" }));
}
}
}
I have a seperate module to assign privilege to the users to access the UI01,UI02,UI03 as following.
Page name Admin Employee Customer
------------------------------------------------
Rating 1 0 0
Map 1 0 0
Sales 1 0 0
*1-allow
*0-Deny access
Currenly All the three UIs allow only Admin role. But I need to set access dynamically to the Controller methods with respective of the privilege set in the above UI.
Edit: I have created Customauthorize attribute for each Page/actionresult and got the result successfully using the method in this link asp.net mvc decorate [Authorize()] with multiple enums
But my problem now is to hide the menus in layout(view) page