Reputation: 241
I need to contact a server to consume a HTTP service.
Trying to reach the service with the browser, using https://example.com/service
I get the basic authentication dialog.
Changing the URL to https://username:[email protected]/service
easily bypasses that.
Trying to do the same using Ajax always results in 401 Unauthorized
though:
$.ajax({
url: 'https://username:[email protected]/service',
// rest repeats
type: "GET",
async: true,
success: function(text) { alert('success'); },
error: function (text) { alert('error') },
complete: function(text) { alert('complete'); }
});
$.ajax({
url: 'https://example.com/service',
username: username,
password: password,
// snip repeat
});
$.ajax({
url: 'https://example.com/service',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic "
+ btoa(username + ":" + password));
},
// snip repeat
});
Upvotes: 11
Views: 31842
Reputation: 467
I struggled with a similar scenario myself.. What did the trick was using jsonp (ugh):
$.ajax({
url: "https://localhost:8443/v1/accounts",
type: 'GET',
dataType: 'jsonp',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic bHVpZ2lAZ21haWwuY29tOmFiYzEyMzQ1');
}
})
Upvotes: 8