我的自定义授权属性始终重定向到未授权页面

时间:2018-10-17 13:52:03

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

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

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

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

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

我写了如下所示的custom属性,一切正常,但最终所有请求都显示了未经授权的访问页面。

任何人都可以帮助您确定并解决问题!

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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分: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;
        }
    }