Verify User Permission on Action Filter or Authroize Filter?

谁说胖子不能爱 提交于 2019-12-06 11:10:48

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!