Unauthorized AJAX request succeeds

2019-07-26 09:37发布

问题:

I have following controller method:

[HttpPost]
[Authorize(Roles="some_role_actual_user_is_NOT_in")
public ActionResult AJAXMethod()
{
    return Json(new { message = "server message");
}

and page with script:

function sendReq()
{
    $.ajax({
        type: "POST",
        data: { somedata: "somedata" },
        url: "/Path/To/AJAXMethod",
        success: onAJAXSuccess,
        error: onAJAXError
    });
}


function onAJAXSuccess(response, status, xhr)
{
    alert("success: " + response.message);
    alert(status);
}

function onAJAXError(xhr,status,error)
{
    alert("error: " + status);
    alert(error);
}

When I call sendReq with user not in the authorized role the AJAX call still suceed - callback onAJAXSuccess is called, but response.message is undefined.

回答1:

This is correct behaviour. The success of an AJAX call is only determined by the fact the the server responded with a 200 OK. You will need to interrogate the returned response yourself to ensure it is in the format you expect.

For example:

if (typeof response.message != "undefined" && response.message != "") {
   // it worked
}
else {
    // didn't work || user did not have access.
}