Unable to authenticate to ASP.NET Web Api service with HttpClient

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);

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).

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"/>

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

UPDATE REGARDING THE USAGE OF FQDN

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. Go to Start –> Run –> regedit
  2. Locate HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_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.

Leave a Comment