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
 
 - 
 Check out stackoverflow.com/a/11960692/1730482.marklap– marklap2015年01月13日 01:53:03 +00:00Commented Jan 13, 2015 at 1:53
- 
 @marklap I alredy checked that question, but i still got the 401 errorSte– Ste2015年01月13日 08:10:37 +00:00Commented Jan 13, 2015 at 8:10
- 
 have you tried the solution I linked to? The second block in that solution specifically?marklap– marklap2015年01月13日 19:35:29 +00:00Commented 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 sentjoozek– joozek2015年02月05日 16:07:31 +00:00Commented 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 requestAnKing– AnKing2016年01月23日 17:56:33 +00:00Commented Jan 23, 2016 at 17:56
1 Answer 1
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
 
 
 
 Lucas Leite 
 
 4774 silver badges6 bronze badges
 
 
 Sign up to request clarification or add additional context in comments.
 
 
 
 Comments
Explore related questions
See similar questions with these tags.
lang-js