27 August 2010

Solving the ASP.Net Double Hop problem

This article is in debt to Andrew Hay's excellent writeup on how he solved his double-hop problem.

The double-hop problem occurs when a central application calls a web-service on a second server, but the credentials are not passed to the second server, causing the web-service call to fail.  This is because IIS does not pass on the credentials to the second machine.

When this happens you will see the error:

System.Net.WebException: The request failed with HTTP status 401: Unauthorized at...

The worst part of this error is that the web service will work from your machine, but not when you move it to the server for testing.

The double-hop will most likely happen if you use the CredentialCache.DefaultNetworkCredentials or CredentialCache.DefaultCredentials to authenticate the service call.

Problem Solved: System.Net.NetworkCredential

The fix is relatively simple:

  • Create a new System.Net.NetworkCredential that uses a service account.  Use this to authenticate the service call.
  • Add the service account to the users group on the target server where the web service is located.

The pseudo code looks like this:

Dataset ds = new DataSet("Grid"); 
using(MyService ws = new MyService) {
     char[] delim = ";".ToCharArray(); 
     string[] creds = ConfiigurationManager.AppSettings["ServiceAcct"].Split(delim);
     ws.Credentials = new System.Net.NetworkCredential(creds[0], creds[1], creds[2]); 
     ds = ws.getDataSet(arg1, arg2);
return ds; 

The Web.Config would have an application setting of "ServiceAccount" with the value "User;Password;Domain".

Follow up with adding the service account to the Users Group on the machine that hosts the web service.  This should solve the