简体   繁体   中英

jQuery.ajax doesn't send Authorization header with OPTIONS request

It appears that jQuery doesn't send along the Authorization header when sending an OPTIONS request before a POST request (or possibly other types). The server I'm trying to reach is returning a 401 status for the OPTIONS request - how can I force jQuery to include the Authorization header, even in this initial request?

$.ajax({
    type: "POST",
    url: url,
    data: postData,
    beforeSend: function ajaxBeforeSend(jqXHR) {
        jqXHR.withCredentials = true;
        jqXHR.setRequestHeader("Authorization", "Basic " + btoa(encodeURIComponent(escape($username.val())) + ":" + encodeURIComponent(escape($password.val()))));
    },
    success: runReportUrlCallback,
    error: runReportErrorCallback
});

I also tried adding username and password to the ajax options, to no avail.

It seems that the 3rd party server has been configured incorrectly without the OPTIONS request in mind.

W3 states that preflight OPTIONS request must:

Exclude user credentials.

User credentials are defined:

The term user credentials for the purposes of this specification means cookies, HTTP authentication, and client-side SSL certificates

See https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0

If the server is in your control then you simply put the OPTIONS request handler in front of your auth check.

If the server is NOT in your control, which seems to be the case here, then you moan at the server administrator explaining they've done it wrong and hope they change it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM