URL 中的用户名和密码

Username and Password in URL

本文关键字:密码 用户 URL      更新时间:2023-09-26

我正在尝试加载一个要求输入用户名和密码的XML文件。

使用的代码如下,我正在尝试在URL中发送用户名和密码:

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

我的页面的完整代码如下所示:

<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>

有人知道我做错了什么吗?

首先,添加此函数以创建授权标头内容:

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

然后,调用该函数并将返回值存储在单独的变量中:

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

最后,将 auth 的值传递给 XMLHttpRequest 对象:

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

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

我最终通过执行以下操作使其工作:

改变:

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

自:

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

有关类似情况,请参阅此问题。如何将Basic Auth与jQuery和AJAX一起使用?请注意,一个答案指出 IE 不支持 URL 中的凭据(正如您尝试执行的那样)。