繁体   English   中英

如何自动使无凭据的Web请求失败,而不提示输入用户名/密码?

[英]How do I auto-fail uncredentialed Web Request rather than prompting for username/password?

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

  • 凭证或非凭证请求进入。
  • 将请求标头传递到辅助api进行身份验证。
  • 请求返回200(凭证良好)或401(凭证不良或丢失)。

我尝试过使用request.PreAuthenticaterequest.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方法(基于此答案 )不包括在内,但可以使用。 具有嵌入式XHR凭据的传入请求按预期成功。 问题是非凭据请求,因此出于我们的目的,可以完全删除CopyHttpParameters函数调用。 我想要的是以下try块完全失败,而没有提示用户登录。 当我直接从浏览器中单击它时,这就是上面的authUrl服务的行为。 进行非凭据的WebRequest调用时如何获得此行为?

问题似乎在这里:

return Request.CreateResponse(HttpStatusCode.Unauthorized);

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

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

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

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

现在,当我返回Unauthorized ,请求仅按预期失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM