12

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
});
Deduplicator
46k7 gold badges73 silver badges125 bronze badges
asked Jan 12, 2015 at 14:19
5
  • Check out stackoverflow.com/a/11960692/1730482. Commented Jan 13, 2015 at 1:53
  • @marklap I alredy checked that question, but i still got the 401 error Commented Jan 13, 2015 at 8:10
  • have you tried the solution I linked to? The second block in that solution specifically? Commented Jan 13, 2015 at 19:35
  • Are you sure you use correct credentials? Try debugging in developer console (F12 in chrome) and make sure the header gets sent Commented Feb 5, 2015 at 16:07
  • I'm having the same issue here. Seems like the solution above doesn't work for me. I'm getting 400 - Bad request Commented Jan 23, 2016 at 17:56

1 Answer 1

9

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');
 }
 })
answered Jan 27, 2016 at 5:49
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.