Windows用户密码验证

时间:2019-02-06 11:08:03

标签: c#

我在c#中有一个表单,可以获取用户名和密码,我需要验证在文本框中键入的内容是否与登录Windows的用户相对应。

使用

WindowsIdentity property ident = WindowsIdentity.GetCurrent ();  
if (ident.Name == txtUsuario.Text)
{  
}

我可以验证名称是否匹配。

但是我该如何检查密码?

1 个答案:

答案 0 :(得分:0)

第1步:我们应该了解我们是否在领域内。

第2步:通过传递用户名和密码来验证凭据。

以下参考文献应添加到项目中

1)System.DirectoryServices(DLL)

2)System.DirectoryServices.AccountManagement(DLL)

    /// <summary>
    ///     Validate username and password combination    
    ///     <para>Following Windows Services must be up</para>
    ///     <para>LanmanServer; TCP/IP NetBIOS Helper</para>
    /// </summary>
    /// <param name="userName">
    ///     Fully formatted UserName.
    ///     In AD: Domain + Username
    ///     In Workgroup: Username or Local computer name + Username
    /// </param>
    /// <param name="securePassword"></param>
    /// <returns></returns>
    public static bool ValidateUsernameAndPassword(string userName, SecureString securePassword)
    {
        bool result = false;

        ContextType contextType = ContextType.Machine;

        if (InDomain())
        {
            contextType = ContextType.Domain;
        }

        try
        {
            using (PrincipalContext principalContext = new PrincipalContext(contextType))
            {
                result = principalContext.ValidateCredentials(
                    userName, 
                    new NetworkCredential(string.Empty, securePassword).Password
                );
            }
        }
        catch (PrincipalOperationException)
        {
            // Account disabled? Considering as Login failed
            result = false;
        }
        catch (Exception)
        {
            throw;
        }

        return result;
    }

    /// <summary>
    ///     Validate: computer connected to domain?   
    /// </summary>
    /// <returns>
    ///     True -- computer is in domain
    ///     <para>False -- computer not in domain</para>
    /// </returns>
    public static bool InDomain()
    {
        bool result = true;

        try
        {
            Domain domain = Domain.GetComputerDomain();
        }
        catch (ActiveDirectoryObjectNotFoundException)
        {
            result = false;
        }

        return result;
    }