简体   繁体   English

C#ASP .NET; 获取登录用户的NetworkCredential对象?

[英]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; 我必须实现以下情形:ASP .NET webapp 1.用户登录2.使用登录用户的凭据,我必须从Sharepoint网站下载一些文件;

Environment: - Right now the web.config is set to impersonation on, and windows auth. 环境:-现在将web.config设置为模拟,并进行Windows身份验证。 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. ,但还必须使用基本身份验证-我使用System.Net.WebClient通过Sharepoint网站的Web服务下载Sharepoint文件,并且此WebClient需要一个Credential对象,这就是为什么我需要NetworkCredential对象的原因。

PS: CredentialCache.DefaultCredentials and CredentialCache.DefaultNetworkCredentials returns a credential with empty username and pw, so I cannot use it for acccessing the Sharpeoint site. PS:CredentialCache.DefaultCredentials和CredentialCache.DefaultNetworkCredentials返回带有空用户名和pw的凭据,因此我不能将其用于访问Sharpeoint站点。 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. 它也不适合获取System.Security.Principal.WindowsIdentity.GetCurrent()或System.Web.HttpContext.Current.User.Identity,因为我只能以这种方式获取用户名,并且要实例化NetworkCredential,我需要一个名称和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. 我正在使用模拟上下文,并且使用了CredentialCache.DefaultNetworkCredentials ,并且将WebClientUseDefaultCredentials为true,到目前为止,这似乎仍然有效。 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: 如果可能的话,您可以尝试使用Forms身份验证,并将.ASPXAUTH cookie以及请求发送到该文件,请参见以下答案:

How do I authenticate a WebClient request? 如何验证WebClient请求?

EDIT Make sure you have this in web.config in order to windows authentication work correctly: 编辑确保您在web.config中具有此功能,以便Windows身份验证正常工作:

<system.web>

    <authentication mode="Windows" />

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

</system.web>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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