代码之家  ›  专栏  ›  技术社区  ›  jgauffin

自定义授权

  •  2
  • jgauffin  · 技术社区  · 15 年前

    我试图通过创建一个基本控制器来使用我自己的授权,并重写OnAuthorization方法。

    当授权失败时,它可以正常工作,但是当我的检查成功时,我会得到一个401页(但是默认的授权检查失败)。

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            var roleAttribute = typeof(AuthorizeAttribute);
            var attributes = filterContext.ActionDescriptor.GetCustomAttributes(roleAttribute, true);
            if (attributes.Length == 0)
                attributes = GetType().GetCustomAttributes(roleAttribute, true);
            if (attributes.Length == 0)
                return;
    
            MvcHelper.Authenticate();
    
    
            foreach (AuthorizeAttribute item in attributes)
            {
                if (!Thread.CurrentPrincipal.IsInRole(item.Roles))
                {
                    filterContext.Result = new RedirectResult("~/Error/Unauthorized/" + "?MissingRole=" + item.Roles);
                    return;
                }
            }
    
            //how do I prevent the default authorization here?
        }
    

    我试过了 filterContext.HttpContext.SkipAuthorization = true; 但没用。

    2 回复  |  直到 15 年前
        1
  •  0
  •   Anuj    14 年前

    我通常在ActionFilter中这样做: https://gist.github.com/e297b435ceb8f022fb95

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentNullException("FilterContext");
    
        if (AuthProvider == null)
            throw new ArgumentNullException("IAuthProvider");
    
        if (AuthProvider.Authenticate(filterContext) == false)
        {
            var req = filterContext.HttpContext.Request;
    
            var response = filterContext.HttpContext.Response;
            response.StatusCode = 401;
            response.AddHeader("WWW-Authenticate", "Basic realm=\"Emergidata\"");
            response.End();
        }
        else
        {
            var controller = filterContext.Controller as IAppController;
            controller.DynamicSession= AuthProvider.AuthProviderContext;
        }
    }
    
        2
  •  0
  •   Tomas Jansson    14 年前