您不必响应 NTLM(集成 Windows 身份验证)质询,如果配置正确,您的浏览器应该会为您完成。一些额外的并发症也可能发生。
第 1 步 - 浏览器
检查浏览器是否可以使用 NTLM Web 应用程序访问和发送您的凭据,或者首先直接点击您正在开发的软件。
第 2 步 - JavaScript withCredentials 属性
当我未能将“withCredentials”属性设置为“true”时,收到的401 Unauthorized错误和描述的症状完全相同。我不熟悉 jQuery,但请确保您设置该属性的尝试成功。
这个例子对我有用:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://localhost:44377/SomeService", true);
xhttp.withCredentials = true;
xhttp.send();
xhttp.onreadystatechange = function(){
if (xhttp.readyState === XMLHttpRequest.DONE) {
if (xhttp.status === 200)
doSomething(xhttp.responseText);
else
console.log('There was a problem with the request.');
}
};
第 3 步 - 服务器端启用 CORS(可选)
我怀疑人们最终遇到这个问题的一个主要原因是他们正在他们的工作站上开发一个组件,而另一个组件托管在其他地方。这会导致跨域资源共享 (CORS)问题。有两种解决方案:
- 在您的浏览器中禁用 CORS - 当您的工作最终将部署在与您的代码正在访问的资源相同的源上时,这对开发很有用。
- 在您的服务器上启用 CORS - 在更广泛的互联网上有大量阅读资料,但这主要涉及发送启用 CORS 的标头。
简而言之,要使用凭据启用 CORS,您必须:
- 发送与所服务页面的来源匹配的“Access-Control-Allow-Origin”标头...这不能是“*”
- 发送值为“true”的“Access-Control-Allow-Credentials”
这是我的 global.asax 文件中的工作 .NET 代码示例。我认为很容易看到正在发生的事情并在需要时翻译成其他语言。
void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.HttpMethod == "OPTIONS")
{
Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
Response.AddHeader("Access-Control-Max-Age", "1728000");
Response.End();
}
else
{
Response.AddHeader("Access-Control-Allow-Credentials", "true");
if (Request.Headers["Origin"] != null)
Response.AddHeader("Access-Control-Allow-Origin" , Request.Headers["Origin"]);
else
Response.AddHeader("Access-Control-Allow-Origin" , "*"); // Last ditch attempt!
}
}