c# - 如何自动失败未经验证的 Web 请求,而不是提示输入用户名/密码?
问题描述
我有一个本地 api 正在向外部 api 发出辅助请求以进行身份验证。在本地 api 工作之前,它通过 WebRequest 将请求标头(应包括 XHR 身份验证标头)转发到身份验证 api。如果请求没有失败(401 未授权),则本地 api 执行其工作。如果第二个请求确实抛出,那么我返回未经授权的。这一切正常 --- 除非我通过本地 api 发出未经认证的请求,否则浏览器会使用本机 Windows 用户名/密码登录弹出窗口提示我。如果我直接针对辅助 api 而不是通过我的本地 api发出相同的未经认证的请求,则该请求将失败并且我永远不会收到提示。我希望我的本地 api 表现出同样的行为:
- 有证书或无证书的请求进来。
- 将请求标头传递给辅助 api 进行身份验证。
- 请求返回 200(凭据良好)或 401(凭据错误或丢失)。
我尝试过使用request.PreAuthenticate
and 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
?
解决方案
问题似乎在这里:
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
,请求就像预期的那样失败。
推荐阅读
- javascript - 角度输出不起作用 - instance[output.propName].subscribe 不是函数
- python - 在 Python 中创建一个 C++ 对象,并将其指针返回给 C++?
- powershell - Remove-S3Bucket : 指定的桶不存在
- neo4j - Neo4j GraphQL graphql.idl 没有生成接口
- c# - 使用终端字体导出 txt 中的希腊字母
- html - 绝对定位的 div 溢出相对父级的边界
- google-apps-script - Telegram Bot:机器人回复什么消息/用户?
- python - 在for循环中比较来自元组的整数
- javascript - 如何获取嵌套对象的键
- c++ - 用于地图的 glm 重载运算符不起作用