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?
The web server user often has different permissions than you do as the website administrator. There are times when you might need the web server user to have the same permissions you do. This is called impersonation: the web server user "impersonates" your site's main file transfer protocol (FTP) user.
Impersonation is independent of the authentication mode configured using the authentication configuration element. The authentication element is used to determine the User property of the current HttpContext. Impersonation is used to determine the WindowsIdentity of the ASP.NET application.
Impersonation allows machine to machine impersonation, so the client browser and the server are on the same page when it comes to the impersonation.
User Impersonation allows Administrators to access and operate as if they were logged in as that User. Administrators can impersonate other authenticated users for testing purposes and view impersonation logs.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With