在 C# 中使用 Windows 用户名密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4516637/
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
using windows username password in C#
提问by Rajkishor Sahu
how i can use windows stored username and password in my C# APP. I am looking for method which returns bool state of successful login. means :
我如何在我的 C# APP 中使用 Windows 存储的用户名和密码。我正在寻找返回成功登录的布尔状态的方法。方法 :
bool isCredentialValid = CheckLogin(username, password);
so according to bool value I can show proper message.
所以根据 bool 值,我可以显示正确的消息。
Updated
更新
class Program
{
static void Main(string[] args)
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine);
Console.WriteLine("Enter username : ");
string user = Console.ReadLine();
Console.WriteLine("Enter password : ");
string pass = Console.ReadLine();
bool isValid = pc.ValidateCredentials(user, pass);
Console.WriteLine("State : {0}",isValid);
Console.ReadLine();
}
}
this code is not working. when i enable Guest accountit shows true for every login and when i disable Guest accountit does not verifies even existing account. Any help would be appreciated.
此代码不起作用。当我启用来宾帐户时,它对每次登录都显示为真,当我禁用来宾帐户时,它甚至不验证现有帐户。任何帮助,将不胜感激。
回答by VinayC
Have a look at PrincipalContext.ValidateCredentialsmethod. For example,
看看PrincipalContext.ValidateCredentials方法。例如,
PrincipalContext pc = new PrincipalContext(ContextType.Domain);
bool isCredentialValid = pc.ValidateCredentials(username, password);
for local accounts, use ContextType.Machine.
对于本地帐户,请使用 ContextType.Machine。
Yet another way would be using win32 api LogonUserfunction
另一种方法是使用 win32 api LogonUser函数
回答by PawanS
Add using System.Security.Principal;
添加 using System.Security.Principal;
//for current Username full
string str = WindowsIdentity.GetCurrent().Name;
Then u can use this username for authentication. For password it is different.
然后你可以使用这个用户名进行身份验证。对于密码,它是不同的。