记录C#的一次域账号与密码的登录验证
使用域名验证
public const int LOGON32_LOGON_INTERACTIVE = 2; public const int LOGON32_PROVIDER_DEFAULT = 0; WindowsImpersonationContext impersonationContext; [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] public extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken); /// <summary> /// 输入用户名、密码、登录域判断是否成功 /// </summary> /// <param name="userName">账户名称</param> /// <param name="password">账户密码</param> /// /// <param name="domain">要登录的域</param> /// <returns>成功返回true,否则返回false</returns> public bool CheckValidUser(String userName, String password, String domain = "tw.dinkle.com.tw") { // tw.dinkle.com.tw 当时在无线网的时候,解析出来的IP是立洋:192.168.11.13 // tw.dinkle.com.tw 当时在有线网的时候,解析出来的IP是昆山:192.168.21.10 //HQDC01.tw.dinkle.com.tw 当时在有线网的时候,解析出来的IP是台北:192.168.1.33 WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext != null) return true; else return false; } else return false; } else return false; }
使用域名IP地址验证
注意:需要引用System.DirectoryServices.dll
/// <summary> /// 通过IP地址验证 域名信息是否成功 /// </summary> /// <param name="userName">账户名称</param> /// <param name="password">账户密码</param> /// <param name="domainIp">要登录的域对应的IP地址</param> /// <returns>成功返回true,否则返回false</returns> public bool CheckValidUserByDoMainIp(String userName, String password, String domainIp = "192.168.1.33") { using (DirectoryEntry directoryEntry = new DirectoryEntry(@"LDAP://" + domainIp, userName, password)) { DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry); directorySearcher.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + userName + "))"; directorySearcher.PropertiesToLoad.Add("cn"); directorySearcher.SearchRoot = directoryEntry; directorySearcher.SearchScope = SearchScope.Subtree; SearchResult result = null; try { result = directorySearcher.FindOne(); } catch //(Exception) { return false; } if (result != null)//验证成功 { DirectoryEntry directoryEntryTemp = result.GetDirectoryEntry(); if (directoryEntryTemp == null) return false; string userID = directoryEntryTemp.Username; if (string.IsNullOrEmpty(userID)) return false; if (userID.ToUpper() != userName.ToUpper()) return false; return true; } else return false; } }