1

I am trying to load an XML file that asks for a username and password.

The code I'm using is as follows that I am trying to send the username and password in the URL:

xmlhttp.open("POST","http://admin:admin@192.168.0.5/myfile.xml",false);

The full code of my page looks like this:

<html>
<body>

<textarea id="test1" name="test1" cols="90" rows="30">
XML file will be displayed here
</textarea><br>

<script type="text/javascript">

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }


  xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("test1").value=xmlhttp.responseText;
     } else
     {
     alert('Panel not communicating.Reason: '+xmlhttp.status);
     }
   }

xmlhttp.open("POST","http://admin:admin@192.168.0.5/myfile.xml",false);
xmlhttp.send();

</script>
</body>
</html>

Anyone know what I am doing wrong?

Jari
  • 2,152
  • 13
  • 20
Aaron
  • 3,389
  • 12
  • 35
  • 48
  • what error are you getting? are you sure that the remote server accepts HTTP Basic Auth? – Jim Deville Jul 02 '12 at 05:51
  • So what happens when you type the URL into a browser window? – Michael Jul 02 '12 at 05:51
  • I don't get any error messages it just sits there, but if I remove the username and password from the URL code it will ask for a username and password which I can manually enter in and it works fine, but I want to do it automatically. any ideas? – Aaron Jul 02 '12 at 05:53
  • i think you need to pass them in a header instead of the url – dbrin Jul 02 '12 at 05:54
  • what do you mean by that?? I am not sure what you mean by that – Aaron Jul 02 '12 at 05:57

3 Answers3

1

First, add this function to create the authorization header contents:

function make_base_auth(user, password)
{
  var tok = user + ':' + pass;
  var hash = Base64.encode(tok);
  return "Basic " + hash;
}

Then, call the function and store the return value in a separate variable:

var auth = make_basic_auth('admin', 'admin');

Lastly, pass the value of auth to the XMLHttpRequest object:

xmlhttp.setRequestHeader('Authorization', auth);
xmlhttp.send();

Attribution: http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

I ended up getting it working by doing the following:

Change:

xmlhttp.open("POST","http://admin:admin@192.168.0.5/myfile.xml",false); 

To:

xmlhttp.open("POST","http://admin:admin@192.168.0.5/myfile.xml",false,"username","password");
Aaron
  • 3,389
  • 12
  • 35
  • 48
0

See this question for a similar scenario. How to use Basic Auth with jQuery and AJAX? Note one answer states that IE does not support credentials in a URL (as you are attempting to do).

Community
  • 1
  • 1
dbrin
  • 15,525
  • 4
  • 56
  • 83