且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法使用 HttpClient 对 ASP.NET Web Api 服务进行身份验证

更新时间:2022-04-27 23:29:18

我已经调查了 HttpClientHandler 的源代码(我能够得到的最新版本),这是可以在 SendAsync 方法中找到的:

I have investigated the source code of HttpClientHandler (the latest version I was able to get my hands on) and this is what can be found in SendAsync method:

// BeginGetResponse/BeginGetRequestStream have a lot of setup work to do before becoming async
// (proxy, dns, connection pooling, etc).  Run these on a separate thread.
// Do not provide a cancellation token; if this helper task could be canceled before starting then 
// nobody would complete the tcs.
Task.Factory.StartNew(startRequest, state);

现在,如果您在代码中检查 SecurityContext.IsWindowsIdentityFlowSuppressed() 的值,您很可能会得到正确的结果.结果 StartRequest 方法在新线程中使用 asp.net 进程的凭据(而不是模拟用户的凭据)执行.

Now if you check within your code the value of SecurityContext.IsWindowsIdentityFlowSuppressed() you will most probably get true. In result the StartRequest method is executed in new thread with the credentials of the asp.net process (not the credentials of the impersonated user).

有两种可能的方法.如果你有权访问你的服务器 aspnet_config.config,你应该设置以下设置(在 web.config 中设置似乎没有效果):

There are two possible ways out of this. If you have access to yours server aspnet_config.config, you should set following settings (setting those in web.config seems to have no effect):

<legacyImpersonationPolicy enabled="false"/>
<alwaysFlowImpersonationPolicy enabled="true"/>

如果您无法更改 aspnet_config.config,则必须创建自己的 HttpClientHandler 来支持这种情况.

If you can't change the aspnet_config.config you will have to create your own HttpClientHandler to support this scenario.

关于 FQDN 使用的更新

您在此处遇到的问题是 Windows 中的一项功能,旨在防止反射攻击".要解决此问题,您需要在尝试访问服务器的计算机上将您尝试访问的域列入白名单.请按照以下步骤操作:

The issue you have hit here is a feature in Windows that is designed to protect against "reflection attacks". To work around this you need to whitelist the domain you are trying to access on the machine that is trying to access the server. Follow below steps:

  1. 转到开始 --> 运行 --> regedit
  2. 找到HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0 注册表项.
  3. 右键单击它,选择新建,然后选择多字符串值.
  4. 输入 BackConnectionHostNames (ENTER).
  5. 右键单击刚刚创建的值并选择修改.
  6. 将本地计算机上站点的主机名放入值框中,然后单击确定(每个主机名/FQDN 都需要在自己的行上,没有通配符,名称必须完全匹配).
  7. 保存一切并重启机器
  1. Go to Start --> Run --> regedit
  2. Locate HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0 registry key.
  3. Right-click on it, choose New and then Multi-String Value.
  4. Type BackConnectionHostNames (ENTER).
  5. Right-click just created value and choose Modify.
  6. Put the host name(s) for the site(s) that are on the local computer in the value box and click OK (each host name/FQDN needs to be on it's own line, no wildcards, the name must be exact match).
  7. Save everything and restart the machine

您可以在此处阅读有关该问题的完整知识库文章.

You can read full KB article regarding the issue here.