I use to write custom action filter attribute so that on the action call this method is called and i check in it if user role allows him to call this action or not.
You have to write custom action filter attribute same way but you have to write your own business logic in CheckAccessRight method:
public class AuthorizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string actionName = filterContext.ActionDescriptor.ActionName;
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
if (!CheckAccessRight(actionName, controllerName))
{
string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
}
else
{
base.OnActionExecuting(filterContext);
}
}
private bool CheckAccessRight(string Action, string Controller)
{
if (HttpContext.Current.Session["userId"] != null)
{
string userID = HttpContext.Current.Session["userId"].ToString();
using (var db = new cloud_clinicEntities())
{
assignment objAss = null;
if (HttpContext.Current.Session["AccountType"].ToString() == "lab")
{
objAss = db.assignments.SingleOrDefault(model => model.userid == userID);
}
else
{
objAss = db.assignments.SingleOrDefault(model => model.employeeId == userID);
}
String UserRole = objAss.itemname;
itemchildren objChild = db.itemchildrens.SingleOrDefault(model => model.parent == UserRole && model.child == Controller + " " + Action);
if (objChild != null)
{
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
}
And then use this attribute on the actions like this:
[AuthorizationAttribute]
public ActionResult MyAction()
{
}