【问题标题】:My Custom Authorize Attribute Always Redirects to Un authroized page我的自定义授权属性总是重定向到未经授权的页面
【发布时间】:2018-10-17 13:52:02
【问题描述】:

我正在为一项需求编写自定义授权属性。

根据要求,我需要为该特定操作方法传递所有允许的角色,如下所示。

    [MyAuthorize("Admin,Reviewer")]
    public ActionResult GetFXSelldownSummaryData()
    {
        var model = (new FXSelldownSummaryBLL()).GetFXSelldownSummaryData();
        return View(model);
    }

当用户登录时,应将登录的用户角色与所有允许的角色进行比较(在上面的代码中,所有允许的角色是Admin,和Reviewer)。如果角色匹配,用户可以看到视图,否则页面应该导航到未授权页面。

我已经编写了如下的自定义属性,一切正常,但我最终得到了所有请求的未经授权的访问页面。

任何人都可以帮助识别和解决问题!

namespace MyRequirement
{

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        readonly string allowedRoles;
        public MyAuthorizeAttribute(string allowedRoles)
        {
            this.allowedRoles = allowedRoles;
        }

        public System.Collections.Generic.List<string> AllowedRoles
        {
            get
            {
                return this.allowedRoles.Split(',').ToList();
            }
        }

        private bool AuthorizeRole(AuthorizationContext filterContext)
        {
            var context = filterContext.RequestContext.HttpContext;
            PnLUserDetails userDetails = System.Web.HttpContext.Current.Session["PnLUserDetails"] as PnLUserDetails;
            string loggedInUserRole = userDetails.Role;
            if (AllowedRoles.Contains(loggedInUserRole))
                return true;
            return false;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext == null)
                throw new ArgumentException("filterContext");
            bool authStatus = AuthorizeRole(filterContext);
            if(!authStatus)
            {
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }
        }
    }
}

【问题讨论】:

    标签: asp.net-mvc asp.net-identity-3


    【解决方案1】:

    删除对

    的调用
    base.OnAuthorization(filterContext);
    

    这样改代码

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // This line is not needed, you are handling the authorization
            // This is the line that will give you the unauthorized access by default
            // base.OnAuthorization(filterContext);
            if (filterContext == null)
                throw new ArgumentException("filterContext");
            bool authStatus = AuthorizeRole(filterContext);
            if(!authStatus)
            {
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      相关资源
      最近更新 更多