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

rad*_*byx 2 javascript authentication ajax asp.net-mvc asp.net-mvc-5

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

我还注册了一个 Global ajaxComplete,用于处理 401 AJAX 请求,但是在HandleUnauthorizedRequest().

问题:我是否必须手动更改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);
    }
}
Run Code Online (Sandbox Code Playgroud)

全局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());
    }
});
Run Code Online (Sandbox Code Playgroud)

“在我找到 ajaxComplete 的解决方案之前,我一直在工作但被黑了。

它检查用户请求是否被授权。缺点是我isAuthorized()每次提出请求时都必须检查。这就是为什么我想使用全局 ajaxComplete,所以我永远不会错过一个。”:

检查用户 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;
};
Run Code Online (Sandbox Code Playgroud)

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

partialViewService.changePartialViewService(url, data)
.done(function (result) {
    if (isAuthorized(result)) {
        // use result
    }
});
Run Code Online (Sandbox Code Playgroud)

Ric*_*ckL 5

是的 - 我没有检查过这个,但尝试添加指示的行。指定代码 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);
    }
}
Run Code Online (Sandbox Code Playgroud)