简体   繁体   中英

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

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.

PS: 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.

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.

You can try to use Forms authentication, if possible for your scenario, and send .ASPXAUTH cookie along with request to that file, see this answer:

How do I authenticate a WebClient request?

EDIT Make sure you have this in web.config in order to windows authentication work correctly:

<system.web>

    <authentication mode="Windows" />

     <authorization>
         <deny users="?"/>
      </authorization>

</system.web>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM