API通过HttpClient使用,当站点A在本地运行时,在我的域帐户(在域P中)下,授予访问权限.在这种情况下,HttpClient实例化如下:
using(var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials: true }))
当A部署到测试服务器时,上面会导致401 Unauthorized响应.测试服务器上的应用程序池在域D中的服务帐户下运行.
明确使用该服务帐户时,如下所示:
var credential = new NetworkCredential("service-account","password","D"); var cache = new CredentialCache { { new Uri(apiServerUri),"NTLM",credential } }; var handler = new HttpClientHandler { Credentials = cache }; using(var client = new HttpClient(handler)) ...
再次在本地运行站点A,仍然可以访问.通过浏览器直接访问API并指定服务帐户凭据时,也会授予访问权限.日志表明它绝对是用于访问API的服务帐户.
将上述部署回测试服务器仍然会导致401 Unauthorized.
将站点A部署到IIS的本地实例,也成功使用了B的API.
在本地运行站点B,然后在本地通过站点A访问它,导致401 Unauthorized.
通过部署A的测试服务器上的浏览器访问API,并指定服务帐户凭据,也会提供401 Unauthorized.
我不确定从哪里开始 – 我在代码中遗漏了一些东西以使其正常工作吗?或者它可能是IIS或AD问题?
解决方法
站点B在IIS中有一个额外的主机绑定设置,以侦听localhost:12345.站点A已配置为连接到该端点,而不是站点B的域名.身份验证现在可以正常工作.
如果有人能解释为什么会这样,我会感兴趣 – 我不喜欢’魔术’修复.
编辑
似乎this kb article可能是导致此行为的原因.特别:
When you use the fully qualified domain name (FQDN) or a custom host
header to browse a local Web site that is hosted on a computer that is
running Microsoft Internet Information Services (IIS) 5.1 or a later
version,you may receive an error message that resembles the
following: HTTP 401.1 – Unauthorized: logon Failed This issue occurs
when the Web site uses Integrated Authentication and has a name that
is mapped to the local loopback address
和
Therefore,authentication fails if the FQDN or the custom host header that you use does not match the local computer name.