9

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:password@example.com/service easily bypasses that.

Trying to do the same using Ajax always results in 401 Unauthorized though:

$.ajax({
    url: 'https://username:password@example.com/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
});
Deduplicator
  • 41,806
  • 6
  • 61
  • 104
Ste
  • 221
  • 1
  • 3
  • 9

1 Answers1

8

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');
        }
    })
Lucas Leite
  • 447
  • 4
  • 6