C# ASP .NET; Get the NetworkCredential Object for the logged in user?

user1307533 picture user1307533 · Oct 6, 2013 · Viewed 10.9k times · Source

I have to implement the following scenario: ASP .NET webapp 1. User logs in 2. With the logged in user's credentials I have to download some files from a Sharepoint site;

Environment: - Right now the web.config is set to impersonation on, and windows auth. on, but also have to work with basic authentication - I use a System.Net.WebClient to download Sharepoint files using the Sharepoint site's web services, and this WebClient needs a Credential object, that's why I need the NetworkCredential object.

P.S: CredentialCache.DefaultCredentials and CredentialCache.DefaultNetworkCredentials returns a credential with empty username and pw, so I cannot use it for acccessing the Sharpeoint site. It is also not suitable to get System.Security.Principal.WindowsIdentity.GetCurrent() or System.Web.HttpContext.Current.User.Identity, because i can get only a username this way, and for instantiating a NetworkCredential I need a uname and pw.

Answer

user1307533 picture user1307533 · Oct 15, 2013

FYI, I think I've managed to solve the issue; I'm using an impersonation context, and I use the CredentialCache.DefaultNetworkCredentials, and I set the WebClient's UseDefaultCredentials to true, and this seems to be working so far. So:

WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
using (identity.Impersonate())
{
    webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
    webClient.UseDefaultCredentials = true;
}

This worked for me.