简体   繁体   中英

Getting NetworkCredential for current user (C#)

I'm trying to invoke a webservice from a console application, and I need to provide the client with a System.Net.NetworkCredential object.
Is it possible to create a NetworkCredential object for the user that started the application without prompting for username/password?

If the web service being invoked uses windows integrated security, creating a NetworkCredential from the current WindowsIdentity should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.

Edit: To get the credentials for the current identity, use the following:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

您可以使用System.Security.Principal.WindowsIdentity.GetCurrent()获取用户名,但无法获取当前用户密码!

If you are using HttpClient , you can use it in the following way to authenticate as the current user:

var httpClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

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