asp.net 利用DirectoryEntry来验证用户以及开机密码

代码有借鉴网上其他

命名空间:System.DirectoryServices

 

.NET Framework

4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0 1.1

 

一:匹配输入信息,如用户名,密码


        public static string Verify_PowerOnPwd(string userId, string userPwd)
        {
            string retmsg = "success";
            string strADPath = "LDAP://10.133.2.202";//目录地址  如XXXX.com或133.134.0.1
            try
            {
                DirectoryEntry entry = new DirectoryEntry(strADPath, userId, userPwd);
                DirectorySearcher search = new DirectorySearcher(entry); //创建DirectoryEntry对象的搜索对象
                search.Filter = "(SAMAccountName=" + userId + ")";  //过滤条件为登录帐号=user
                SearchResult result = search.FindOne(); //查找第一个
                if (null == result)   //没找到
                {
                    retmsg = "cancel";
                }
            }
            catch (DirectoryServicesCOMException ex)
            {
                if (ex.ErrorCode == -2147023570)
                {
                    retmsg = ex.Message.ToString();// "用戶名/密碼錯誤"; 
                }
                //throw ex; 
            }

            return retmsg;
        }

二:获取目录下所有信息

StringBuilder sb = new StringBuilder(); 
        try { DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}/OU={1},DC={2},DC={3}", domain, root, domain.Split('.')[0], domain.Split('.')[1]), domain + @"\" + user, pwd); 
            DirectorySearcher mySearcher = new DirectorySearcher(entry); 
            mySearcher.Filter = ("(objectClass=organizationalUnit)"); // 查找条件是entry 下的部门 
            sb.Append("[{id:'0',pid:null,text:'" + root + "',expand:true}"); 
            int i = 1; 
            foreach (SearchResult resEnt in mySearcher.FindAll()) //遍历所有部门 
            { 
                string _a = resEnt.GetDirectoryEntry().Name.Split('=')[1]; 
                if (_a != root) { sb.Append(",{id:'" + i.ToString() + "',pid:'0',text:'" + _a + "'}"); 
                    DirectorySearcher m1 = new DirectorySearcher(resEnt.GetDirectoryEntry()); //查找用户对象 
                    m1.Filter = ("(objectClass=user)"); //查找条件是所有用户 
                    foreach (SearchResult r1 in m1.FindAll()) //遍历该部门下的所有用户 
                    { sb.Append(",{ id:'" + r1.GetDirectoryEntry().Properties["sAMAccountName"][0].ToString() + "',pid:'" + i.ToString() + "',text:'" + r1.GetDirectoryEntry().Properties["Name"][0].ToString() + "'}"); 
                    } i++; 
                } 
            } 
            sb.Append("]");
        }catch(Exception)
        {}

 

你可能感兴趣的:(asp.net 利用DirectoryEntry来验证用户以及开机密码)