Use C# to verify domain accounts (Domain):
1. Use dynamic library
[DllImport("")] private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); const int LOGON32_LOGON_INTERACTIVE = 2; //Verify account legality through the networkconst int LOGON32_PROVIDER_DEFAULT = 0; //Use the default Windows 2000/NT NTLM verification party public static bool CheckADAccount(string account, string password) { IntPtr tokenHandle = new IntPtr(0); tokenHandle = ; string domainName = "dpbg"; if (LogonUser(account, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle)) return true; return false; }
Note that using this dynamic library may cause the service Local Security Authority Process memory to rise abnormally and cannot be recycled.
2. Use
/// <summary> /// Verify the domain account/// </summary> /// <param name="account">account</param>/// <param name="password">Password</param>/// <param name="domain">Domain</param>/// <param name="name">name</param>/// <returns></returns> public static bool CheckADAccountNew(string account, string password, string domain, out string name) { name = ""; using (DirectoryEntry deUser = new DirectoryEntry(@"LDAP://" + domain, account, password)) { DirectorySearcher src = new DirectorySearcher(deUser); = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + account + "))"; ("cn"); = deUser; = ; try { SearchResult result = (); if (result != null)//Verification is successful { if (["cn"] != null)//Get user information based on actual attributes { name = ["cn"][0].ToString(); } return true; } return false; } catch { return false; } } }
Note that if there are many accounts in the domain, the speed of verifying non-existent accounts is slower and the validity period of the password will not be verified.
III. Use
/// <summary> /// Verify the domain account/// </summary> /// <param name="account">account</param>/// <param name="password">Password</param>/// <param name="domain">Domain</param>/// <param name="name">name</param>/// <returns></returns> public static bool CheckADAccountNew(string account, string password, string domain, out string name) { name = ""; using (var domainContext = new PrincipalContext(, domain)) { using (var foundUser = (domainContext, , account)) { if (foundUser == null) { return false; } name = ; if ((account, password)) { return true; } else { return false; } } } }
Note that this method will not verify the validity period of the password
This is the article about the implementation of C# domain account verification. For more related C# domain account verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!