/// <summary> /// AD域验证服务 /// </summary> public static class ActiveDirectoryService { //轻型目录访问协议 private static readonly string agreement = "LDAP://"; //DNS AD域名 域地址 private static readonly string ADPath = "192.168.9.9"; //管理员用户名 private static readonly string ADAccount = "user"; //管理员密码 private static readonly string AdPwd = "234567t"; //禁用用户帐户 private static readonly int ACCOUNTDISABLE = 0x0002; /// <summary> /// 根据用户名进行AD域登录校验 /// </summary> /// <param name="UserName"></param> /// <returns></returns> public static string ActiveDirectoryLogin(string UserName) { using (DirectoryEntry adsEntry = new DirectoryEntry(agreement + ADPath, ADAccount, AdPwd, AuthenticationTypes.Secure)) { if (adsEntry is null) { Console.WriteLine("test"); } using (DirectorySearcher adsSearch = new DirectorySearcher(adsEntry)) { adsSearch.Filter = "(&(objectCategory=user)(sAMAccountName=" + UserName + "))"; SearchResultCollection adsSearchResult = adsSearch.FindAll(); //判断域用户是否存在 if (adsSearchResult.Count != 0 ) { using (DirectoryEntry deEntity = new DirectoryEntry(adsSearch.FindOne().Path, ADAccount, AdPwd, AuthenticationTypes.Secure)) { int ADUserDisabled = Convert.ToInt32(ACCOUNTDISABLE); int flagExists = Convert.ToInt32(deEntity.Properties["userAccountControl"][0]) & ADUserDisabled; if (flagExists > 0) { return "域用户已被禁用,不可登录"; } else { return null; } } } else { return "域用户不存在,不可登录"; } } } } }