首页 > 解决方案 > 如何自动失败未经验证的 Web 请求,而不是提示输入用户名/密码?

问题描述

我有一个本地 api 正在向外部 api 发出辅助请求以进行身份​​验证。在本地 api 工作之前,它通过 WebRequest 将请求标头(应包括 XHR 身份验证标头)转发到身份验证 api。如果请求没有失败(401 未授权),则本地 api 执行其工作。如果第二个请求确实抛出,那么我返回未经授权的。这一切正常 --- 除非我通过本地 api 发出未经认证的请求,否则浏览器会使用本机 Windows 用户名/密码登录弹出窗口提示我。如果我直接针对辅助 api 而不是通过我的本地 api发出相同的未经认证的请求,则该请求将失败并且我永远不会收到提示。我希望我的本地 api 表现出同样的行为:

我尝试过使用request.PreAuthenticateand request.Credentials,但我尝试过的任何值似乎都无法阻止弹出窗口出现。

// Create the authorization request object
string authUrl = @"https://auth-service-url.com/api/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(authUrl);

// Relay any params from this request onto the outgoing authorization request
CopyHttpParameters(request);

// Retrieve the response
try {
    WebResponse response = request.GetResponse();
    // If GetResponse doesn't throw, then the user is authorized
    return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception)
{
    // If GetResponse throws, then the user is unauthorized
    return Request.CreateResponse(HttpStatusCode.Unauthorized);
}

上面的CopyHttpParameters方法(基于this answer)不包括在内,但它有效。带有嵌入式 XHR 凭据的传入请求按预期成功。问题在于未经认证的请求,因此出于我们的目的,CopyHttpParameters可以完全删除函数调用。我想要的是让下面的 try 块简单地失败,而不提示用户登录。这就是authUrl我直接从浏览器点击上面的服务时的行为方式。当我拨打未经授权的电话时,如何获得这种行为WebRequest

标签: c#xmlhttprequest

解决方案


问题似乎在这里:

return Request.CreateResponse(HttpStatusCode.Unauthorized);

这与windowsAuthentication我的applicationhost.config似乎正在触发弹出窗口相结合。

将以下内容添加到我的 Web.config 似乎可以抑制弹出窗口:

<location path="api">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>

location块可能不是必需的,但我不想覆盖站点范围的默认值以防万一。这可确保仅为我的 api 路由关闭 Windows 身份验证。

现在,当我返回时Unauthorized,请求就像预期的那样失败。


推荐阅读