【问题标题】:Windows forms authentication C# [closed]Windows 窗体身份验证 C# [关闭]
【发布时间】:2016-02-24 14:02:45
【问题描述】:

我正在尝试将 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;
    }

}

【问题讨论】:

  • 如果您说您研究过它,这对您没有帮助吗[code.msdn.microsoft.com/windowsdesktop/…?
  • 您能否解释一下场景,您需要为客户服务或独立服务的场景。还要提供你已经尝试过的代码的sn-p。
  • 您发布的链接不存在。

标签: c# authentication windows-forms-designer


【解决方案1】:

考虑到您需要一个独立的应用程序来进行 Windows 身份验证。

第 1 步:获取用户名:来自

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

如果您使用正确的用户名和密码,它会给出结果,希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    相关资源
    最近更新 更多