我正在尝试将Windows身份验证添加到我的登录表单中。我对认证进行了研究,但我所看到的只是对asp.net的认证。有人可以帮助我,我有点被困在这里。
我在网上找到了一些帮助,但它的一半...需要帮助才能在下面的代码中向数据库添加连接字符串和查询。
public partial class Form1 : Form
{
[System.Runtime.InteropServices.DllImport("advapi32.dll")]
public static extern bool LogonUser(string userName, string domainName, string password);
public Form1()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
bool issuccess = false;
string username = GetloggedinUserName();
if (username.ToLowerInvariant().Contains(txtUserName.Text.Trim().ToLowerInvariant()))
{
issuccess = IsValidateCredentials(txtUserName.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
}
if (issuccess)
MessageBox.Show("Successfully Login !!!");
else
MessageBox.Show("User Name / Password is invalid !!!");
}
private string GetloggedinUserName()
{
System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
return currentUser.Name;
}
private bool IsValidateCredentials(string userName, string password)
{
IntPtr tokenHandler = IntPtr.Zero;
bool isValid = LogonUser(userName, domain, password, 2, 0, ref tokenHandler);
return isValid;
}
}
答案 0 :(得分:1)
考虑到您需要一个独立的Windows身份验证应用程序。
第1步:GetUserName:来自
System.Security.Principal.WindowsIdentity.GetCurrent().Name;
or
Environment.UserName
你可以从here 获得它们之间的差异
第2步:现在使用
[System.Runtime.InteropServices.DllImport("advapi32.dll")]
public static extern bool LogonUser(string userName, string domainName,string password, int LogonType, int LogonProvider, ref IntPtr phToken);
如果您使用正确的用户名和密码,它会给出结果,希望这有帮助。