Cross-domain ajax request basic authentication
28,049
Solution 1
Pass username and password like following code,
$.ajax({
type: "GET",
xhrFields: {
withCredentials: true
},
dataType: "jsonp",
contentType: "application/javascript",
data: myData,
async: false,
crossDomain: true,
url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData",
success: function (jsonData) {
console.log(jsonData);
},
error: function (request, textStatus, errorThrown) {
console.log(request.responseText);
console.log(textStatus);
console.log(errorThrown);
}
username: username,
password: password,
});
Solution 2
$.ajax({
url: 'yoururl',
username : username,
password :password,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: "text",
xhrFields:
{
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
}
});
Author by
mike44
Updated on June 24, 2021Comments
-
mike44 almost 3 years
I'm making cross-domain ajax request to get some data. The REST service have
Basic authentication
(set throughIIS
).$.ajax({ type: "GET", xhrFields: { withCredentials: true }, dataType: "jsonp", contentType: "application/javascript", data: myData, async: false, crossDomain: true, url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData", success: function (jsonData) { console.log(jsonData); }, error: function (request, textStatus, errorThrown) { console.log(request.responseText); console.log(textStatus); console.log(errorThrown); } });
When I make this request, it prompts me to enter credentials & I have to manually enter credentials to get the response. Can we send those credentials through the request itself?
-
Dave Newton over 9 yearsI'm not excited about this answer, and here's why: it's redundant (question was answered about a half-year earlier) and it's redundant (jQuery handles the auth stuff for you, AFAICT). If I'm wrong about the latter, edit the answer, and I'll delete this comment.
-
rodrigobartels over 7 yearsUsing the beforeSend property worked for me, since username and password for some reason weren't adding the Authorization header. Just in case it helps anyone.