9

I need to pass a NetworkCredential object with the credentials of the currently impersonated user to a web service from an asp.net application.
My code looks like this:

WindowsIdentity windowsIdentity = HttpContext.Current.User.Identity as WindowsIdentity;
WindowsImpersonationContext context = windowsIdentity.Impersonate();
try {
    var client = GetClient();
    client.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
    Log("WindowsIdentity = {0}", windowsIdentity.Name);
    Log("DefaultNetworkCredentials = {0}", CredentialCache.DefaultNetworkCredentials.UserName);
    client.DoSomething();
} finally {
    context.Undo();
}

I had understood that CredentialCache.DefaultNetworkCredentials should give the credentials of the currently impersonated user, but it is not the case.
The log messages I get are

WindowsIdentity = TESTDOMAIN\TESTUSER
DefaultNetworkCredentials = 

Am I doing something wrong? If so, how do you get a NetworkCredential object for the currently impersonated user?

Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
  • 3
    Is this not a manifestation of the double-hop problem? http://blogs.msdn.com/knowledgecast/archive/2007/01/31/the-double-hop-problem.aspx – Rich Jan 14 '10 at 10:38
  • Yes, seems related to the double-hop problem as the secondary token you will have in ASP won't give you network credentials. – Dirk Vollmar Jan 14 '10 at 11:30

2 Answers2

4

A somewhat lengthy article in MSDN explaining the options to obtain network credentials in ASP:

How To: Use Impersonation and Delegation in ASP.NET 2.0

Another blog article on the topic (though I didn't check whether the solution actually works:

.NET (C#) Impersonation with Network Credentials

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
  • I ask a related question would you please check it: http://stackoverflow.com/questions/18842970/asp-net-imperonate-in-netframework-2-vs-netframework-4 – Saeid Alizade Sep 17 '13 at 07:28
  • The second article defines a class which requires the password to be entered and sent as a parameter. I think the benefit of impersonation would be in a Windows Authentication mode being able to use the Principal and Identity to access network resources. As the next poster stated, the simple method is not possible beyond the local machine (without kerberos, which is not simple...) – Thronk Oct 07 '13 at 20:07
1

It's not possible to use the asp.net impersonated user (Current.User.Identity) for network authentication, it only works locally.

Pent Ploompuu
  • 5,364
  • 1
  • 27
  • 47