问题
I'm working on a consumer for a self-made API and having serious difficulties with setting the Authorization header. I am using JQuery for the Ajax requests, but the 'beforeSend' does not work at all (using fiddler to examine the requests)
This is my beforeSend code:
$.ajax({
type: "GET",
url: url+"/Projects",
contentType: "application/json; charset=utf-8",
beforeSend: function (req) {
req.setRequestHeader("Authorization", AuthBuilder(username, password));
},
success: function (result) {
alert("success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("fail");
}
});
Well if that fails what do you do? Go back to the old way for sending ajax requests... well this doesn't work either...
This is my regular code:
function GET(address, callback, error) {
Request = getXMLHttpObject();
Request.open("GET", url + address, true);
var base64 = Base64.encode(username + ":" + password);
alert(base64);
Request.setRequestHeader("Authorization", "Basic " + base64);
Request.send();
Request.onreadystatechange = function () {
//alert(Request.readyState+" code "+Request.status);
if (Request.readyState == 4 && Request.status == 200) {
callback(jQuery.parseJSON(Request.responseText));
} else if (Request.readyState == 4 && Request.status >= 400) {
error(Request.status, Request.statusText);
}
}
}
Don't mind the fact that I'm not asking for json specifically because the service returns json by default.
In additional info:
- the origin does not matter, the service allows all origins (has been tested and confirmed)
- the Authorization works when set by headers (tested in other clients)
- the Authorization headers just aren't sent
- AuthBuilder(username, password)) gives the correct format of the Basic Auth header content
- the getXMLHttpObject() is just some copy paste code and worked before
any thoughts ?
回答1:
Well I found out what the problem was. The self-made service sent this back to the client as a global header : "Access-Control-Allow-Headers" with only "Content-Type" in it.
This way our clients not using an User Agent (browser) ignored these headers and just sent the header anyway. But the browser tried to optimize the request and said "It won't accept the Authorization header so I'll just cut it before sending." this way is the package is smaller and the service won't allow it anyway (although it did...)
So just adding "Authorization" to the Access Control Allow Headers part of the service made my Javascript/JQuery/Ajax requests send the request header as normal!
来源:https://stackoverflow.com/questions/9820170/ajax-authorization-request-headers-fails-again-and-again