Verify User Permission on Action Filter or Authroi

2019-06-13 06:04发布

问题:

I am developing a website in MVC4. I developed user roles and permissions.

I want to ask where I should check user permission access: in the Custom Action filter, or the Custom Authorization filter?

If user does not have access to the module, then I must show a toaster error message. How do I show this message in an action filter?

回答1:

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()
        {
        }


回答2:

Here's a good article. You can set your own attributes for several roles like admin.