我已经介绍了我的代码一百万次,并找不到我的实现问题..

在自定义权限中我覆盖2方法

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!httpContext.Request.IsAuthenticated)
            return false;
        var routeData = httpContext.Request.RequestContext.RouteData;
        var ctrl = routeData.Values["controller"].ToString();
        var action = routeData.Values["action"].ToString();
        var user = httpContext.User.Identity.Name;
        _logger.Info("[logging all the details]");
        return ctrl == "SomeController";
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext ctx)
    {
        ctx.Result = new ViewResult  { ViewName = "Unauthorized" };
        // base.HandleUnauthorizedRequest(ctx);
     }
.

授权逻辑被嘲笑仅在特定控制器上返回false,并且我介绍了它来验证它是否正常工作。

上面的代码将导致无限循环。在我的日志中,我可以看到那行命中666次(巧合?)..

如果我要调用base.handleunauthorizedRequest(CTX),我得到的只是一个空白页面。所以我反映了基础的作用,这是这个

filterContext.Result = new HttpUnauthorizedResult();
.

所以这解释了为什么它呈现一个空白页面而不是重定向到未被授权的.cshtml。我不确定的是,如果我不打电话,为什么它进入无限循环。

p.s。

我已经验证了如果我置于错误的未经授权的视图,它会出错(但仍然无限期地挂起)

 System.InvalidOperationException: The view 'Unauthorized11' or its master was not found or no view engine supports the searched locations
.

有帮助吗?

解决方案

这里是我最终与之去的实施,它的工作非常好。

    public override void OnAuthorization(AuthorizationContext filterContext)
    {

        base.OnAuthorization(filterContext);

        // this is overriden for kendo menus to hide 
        var ctrl = filterContext.RequestContext.RouteData.GetRequiredString("controller");
        var action = filterContext.ActionDescriptor.ActionName;

        [custom authorization logic on action/ctrl]

        // useful to determine if it's authorizing current controller path or menu links
        var path = filterContext.HttpContext.Request.PhysicalPath;
        _authorizingCurrentPath = path.Contains(ctrl) || path.EndsWith("WebUI") ;


        if (userAuth < requiredAuth)
            HandleUnauthorizedRequest(filterContext);
    }


    protected override void HandleUnauthorizedRequest(AuthorizationContext ctx)
    {
        if (!ctx.HttpContext.User.Identity.IsAuthenticated)
            base.HandleUnauthorizedRequest(ctx);
        else {
            if (_authorizingCurrentPath) {
                // handle controller access
                ctx.Result = new ViewResult { ViewName = "Unauthorized" };
                ctx.HttpContext.Response.StatusCode = 403;
            }
            else {
                // handle menu links
                ctx.Result = new HttpUnauthorizedResult();
                ctx.HttpContext.Response.StatusCode = 403;
            }
        }
    }
.

其他提示

texizeattribute 在动作上下文上设置响应,不调用基本基础,响应永远不会设置,这会导致过滤器重复授权过程,直到设置响应(因此无限循环)。

您可以在 authorizationFilterAttribute 类中。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top