获取当前用户的 NetworkCredential (C#)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/949340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:02:30  来源:igfitidea点击:

Getting NetworkCredential for current user (C#)

c#web-servicesauthentication

提问by Paolo Tedesco

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

我正在尝试从控制台应用程序调用 Web 服务,我需要为客户端提供一个System.Net.NetworkCredential对象。
是否可以NetworkCredential在不提示输入用户名/密码的情况下为启动应用程序的用户创建对象?

采纳答案by jrista

If the web service being invoked uses windows integrated security, creating a NetworkCredentialfrom the current WindowsIdentityshould 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.

如果被调用的 web 服务使用 windows 集成安全,NetworkCredential从当前创建一个WindowsIdentity应该足以允许 web 服务使用当前用户 windows 登录。但是,如果 Web 服务使用不同的安全模型,则没有任何方法可以从当前身份中提取用户密码……这本身就是不安全的,允许您(开发人员)窃取您的用户密码. 您可能需要为您的用户提供某种方式来提供他们的密码,如果您不希望他们重复提供密码,请将其保存在某个安全缓存中。

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");

回答by abatishchev

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent()but there is not way to get current user password!

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