未经授权的AJAX请求返回状态码200而不是401

时间:2016-03-08 09:10:44

标签: javascript ajax asp.net-mvc authentication asp.net-mvc-5

在MVC 5中,我重写HandleUnauthorizedRequest()并检查请求是否来自AJAX。

我还注册了一个全局ajaxComplete,用于处理401 AJAX请求,但在HandleUnauthorizedRequest()之后状态代码仍为200。

问题:我是否必须手动更改filterContext功能中HandleUnauthorizedRequest()的状态代码?

检测到未经授权的AJAX请求

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    if (filterContext.HttpContext.Request.IsAjaxRequest())
    {
        // <-- in here
        filterContext.Result = new JsonResult
        {
            Data = new
            {
                returnUrl = "foo"
            },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
    else
    {
        base.HandleUnauthorizedRequest(filterContext);
    }
}

全球ajax完成注册

$(document).ajaxComplete(function (e, xhr, settings) {
    console.log('xhr.status: "' + xhr.status +'"'); // 200 - i want 401
    if(xhr.status === 401) {
        window.location.replace(urlHelper.getUrlNotAuthorized());
    }
});

&#34;工作但遭到黑客攻击的解决方案,直到找到ajaxComplete的解决方案。

检查用户请求是否已获得授权。缺点是,我必须检查isAuthorized()我提出请求。这就是我想使用全局ajaxComplete的原因,所以我绝不会错过任何一个。&#34;:

检查用户AJAX请求是否已获得授权

isAuthorized = function (result) {
    try {
        var obj = JSON && JSON.parse(result) || $.parseJSON(result);
        // Here, obj can still be a parsed JsonResult, from when getting GetDatatableRows(), so we also need to check on returnUrl which is distinct
        // obj will only contain returnUrl if the JSON was returned from Shield validation
        if (obj && obj.returnUrl) {
            window.location.replace(urlHelper.getUrlNotAuthorized() + '?returnUrl=' + encodeURIComponent(obj.returnUrl));
            return false;
        }
    } catch (e) {
    }
    return true;
};

AJAX请求,其中结果是部分视图或JSON

partialViewService.changePartialViewService(url, data)
.done(function (result) {
    if (isAuthorized(result)) {
        // use result
    }
});

1 个答案:

答案 0 :(得分:4)

是 - 我没有检查过这个,但尝试添加指示的行。指定代码401不会过滤到您想要的结果。 (我怀疑这是由于身份截取代码401具体而言):

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    if (filterContext.HttpContext.Request.IsAjaxRequest())
    {
        // Add this (code 401 does not work)
        filterContext.HttpContext.Response.StatusCode = 412;
        // <-- in here
        filterContext.Result = new JsonResult
        {
            Data = new
            {
                returnUrl = "foo"
            },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
    else
    {
        base.HandleUnauthorizedRequest(filterContext);
    }
}