关于AD校验代码

Posted 干就完了

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于AD校验代码相关的知识,希望对你有一定的参考价值。

引入命名空间:

using System.DirectoryServices;。通过VS可以添加

using System;
using System.Collections.Generic;
using System.Data;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Text;


namespace Woo.Utility
{
    public class ADUtility
    {
        private static string domainName = "192.168.10.188"; //"192.168.2.161"; //"ms.com";
        private static string adAdmin ="administrator"; //"administrator";
        private static string password = "Lh!12345";  //"Woorich```";
        private static string ouName = "Users"; //"Users";
        private DataTable dt = null;//创建一个table



        #region## 同步根组织单位
        /// <summary>
        /// 功能: 同步根组织单位
        /// 创建人:dyk
        /// 创建时间:2013-9-9
        /// </summary>
        /// <param name="entry"></param>
        private void SyncRootOU(DirectoryEntry entry)
        {
            if (entry.Properties.Contains("ou") && entry.Properties.Contains("objectGUID"))
            {
                string rootOuName = entry.Properties["ou"][0].ToString();

                byte[] bGUID = entry.Properties["objectGUID"][0] as byte[];

                string id = BitConverter.ToString(bGUID);

              

                SyncSubOU(entry, id);
            }
        }
        #endregion
        #region 创建一个table
        /// <summary>
        /// 创建一个table
        /// </summary>
        public void CreateTab()
        {
            dt = new DataTable();
            dt.Columns.Add("sAMAccountName");//帐号
            dt.Columns.Add("Name");//姓名
            dt.Columns.Add("mail"); //邮箱地址
            dt.Columns.Add("OU");  //用户组织
            dt.Columns.Add("sn");//
            dt.Columns.Add("givenName");//
            dt.Columns.Add("displayName");//显示名称
            dt.Columns.Add("description");//描述
            dt.Columns.Add("physicalDeliveryOfficeName");//办公室
            dt.Columns.Add("initials");//因为缩写
            dt.Columns.Add("telephoneNumber");//电话号码
            dt.Columns.Add("wWWHomePage");//网页
            dt.Columns.Add("otherTelephone");//其他号码
            dt.Columns.Add("url");//其他网页
            dt.Columns.Add("co");//国家地区
            dt.Columns.Add("st");//省市
            dt.Columns.Add("l");//
            dt.Columns.Add("streetAddress");//街道
            dt.Columns.Add("postOfficeBox");//邮政信箱
            dt.Columns.Add("postalCode");//邮政编码
            dt.Columns.Add("userPrincipalName");//登陆用户名
            dt.Columns.Add("company");//公司
            dt.Columns.Add("department");//部门
            dt.Columns.Add("title");//职务
            dt.Columns.Add("manager");//经理-姓名
            dt.Columns.Add("directReports");//直接下属
            dt.Columns.Add("mobile");//手机
        }
        #endregion

        #region## 同步下属组织单位及下属用户
        /// <summary>
        /// 功能: 同步下属组织单位及下属用户
        /// 创建人:dyk
        /// 创建时间:2013-9-9
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="parentId"></param>
        private void SyncSubOU(DirectoryEntry entry, string parentId)
        {
            if (dt == null)
            {
                CreateTab();//创建dt
            }
           
            foreach (DirectoryEntry subEntry in entry.Children)
            {
                string entrySchemaClsName = subEntry.SchemaClassName;

                string[] arr = subEntry.Name.Split(=);
                string categoryStr = arr[0];
                string nameStr = arr[1];
                string id = string.Empty;

                if (subEntry.Properties.Contains("objectGUID"))   //SID
                {
                    byte[] bGUID = subEntry.Properties["objectGUID"][0] as byte[];

                    id = BitConverter.ToString(bGUID);
                }

          
                switch (entrySchemaClsName)
                {
                    case "organizationalUnit":
                     SyncSubOU(subEntry, id);
                        break;
                    case "user":
                        //string accountName = string.Empty;

                        //if (subEntry.Properties.Contains("samaccountName"))
                        //{
                        //    accountName = subEntry.Properties["samaccountName"][0].ToString();
                        //}
                    DataRow dr = dt.NewRow();
                    dr["sAMAccountName"] = string.Empty;
                    dr["Name"] = string.Empty;
                    dr["mail"] = string.Empty;
                    dr["OU"] = string.Empty;
                    dr["sn"] = string.Empty;
                    dr["givenName"] = string.Empty;
                    dr["displayName"] = string.Empty;
                    dr["description"] = string.Empty;
                    dr["physicalDeliveryOfficeName"] = string.Empty;
                    dr["initials"] = string.Empty;
                    dr["telephoneNumber"] = string.Empty;
                    dr["wWWHomePage"] = string.Empty;
                    dr["url"] = string.Empty;
                    dr["co"] = string.Empty;
                    dr["st"] = string.Empty;
                    dr["l"] = string.Empty;
                    dr["streetAddress"] = string.Empty;
                    dr["postOfficeBox"] = string.Empty;
                    dr["postalCode"] = string.Empty;
                    dr["userPrincipalName"] = string.Empty;
                    dr["company"] = string.Empty;
                    dr["department"] = string.Empty;
                    dr["title"] = string.Empty;
                    dr["manager"] = string.Empty;
                    dr["directReports"] = string.Empty;
                    dr["mobile"] = string.Empty;

                  //  DirectoryEntry user = resEnt.GetDirectoryEntry();
                    if (subEntry.Properties.Contains("sAMAccountName"))
                    {
                        dr["sAMAccountName"] = subEntry.Properties["sAMAccountName"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("Name"))
                    {
                        dr["Name"] = subEntry.Properties["Name"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("mail"))
                    {
                        dr["mail"] = subEntry.Properties["mail"][0].ToString();
                    }

                    if (subEntry.Properties.Contains("sn"))
                    {
                        dr["sn"] = subEntry.Properties["sn"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("givenName"))
                    {
                        dr["givenName"] = subEntry.Properties["givenName"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("displayName"))
                    {
                        dr["displayName"] = subEntry.Properties["displayName"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("description"))
                    {
                        dr["description"] = subEntry.Properties["description"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("physicalDeliveryOfficeName"))
                    {
                        dr["physicalDeliveryOfficeName"] = subEntry.Properties["physicalDeliveryOfficeName"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("initials"))
                    {
                        dr["initials"] = subEntry.Properties["initials"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("telephoneNumber"))
                    {
                        dr["telephoneNumber"] = subEntry.Properties["telephoneNumber"][0].ToString();

                    }
                    if (subEntry.Properties.Contains("wWWHomePage"))
                    {
                        dr["wWWHomePage"] = subEntry.Properties["wWWHomePage"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("url"))
                    {
                        dr["url"] = subEntry.Properties["url"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("co"))
                    {
                        dr["co"] = subEntry.Properties["co"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("st"))
                    {
                        dr["st"] = subEntry.Properties["st"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("l"))
                    {
                        dr["l"] = subEntry.Properties["l"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("streetAddress"))
                    {
                        dr["streetAddress"] = subEntry.Properties["streetAddress"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("postOfficeBox"))
                    {
                        dr["postOfficeBox"] = subEntry.Properties["postOfficeBox"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("postalCode"))
                    {
                        dr["postalCode"] = subEntry.Properties["postalCode"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("userPrincipalName"))
                    {
                        dr["userPrincipalName"] = subEntry.Properties["userPrincipalName"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("company"))
                    {
                        dr["company"] = subEntry.Properties["company"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("department"))
                    {
                        dr["department"] = subEntry.Properties["department"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("title"))
                    {
                        dr["title"] = subEntry.Properties["title"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("manager"))
                    {
                        dr["manager"] = subEntry.Properties["manager"][0].ToString();
                    }
                    if (subEntry.Properties.Contains("directReports"))
                    {
                        dr["directReports"] = subEntry.Properties["directReports"][0].ToString();
                    }

                    if (subEntry.Properties.Contains("mobile"))
                    {
                        dr["mobile"] = subEntry.Properties["mobile"][0].ToString();
                    }


                    if (subEntry.Parent.Name != string.Empty && subEntry.Parent.Name.IndexOf(=) > -1)
                    {
                        //获取用户所在的组织单位
                        dr["OU"] = subEntry.Parent.Name.Split(=)[1];
                    }
                    dt.Rows.Add(dr);

                     
                  break;
                }
            }
        }
        #endregion
        #region 同步AD账号和组织
        /// <summary>
        /// 同步
        /// </summary>
        public void SynAll()
        {

            DirectoryEntry entry = new DirectoryEntry("LDAP://" + domainName, adAdmin, password, AuthenticationTypes.Secure);
            DirectoryEntry rootOU = entry.Children.Find("OU=" + ouName);
            DirectorySearcher mySearcher = new DirectorySearcher(rootOU, "(objectclass=organizationalUnit)"); //查询组织单位                 
            DirectoryEntry root = mySearcher.SearchRoot;   //查找根OU
            SyncRootOU(root);

        }
        #endregion


        #region 同步数据库和AD用户
        /// <summary>
        /// 同步
        /// </summary>
        //public void SynUser(DataTable dtad)
        //{
        //    try
        //    {
        //        var page = new PageInfo<WOO_USER>();
        //        Woo.BLL.WooSetting.User.GetAll(page);
        //        var Ulist = page.List;//数据库list集合
        //        List<string> liscodename = new List<string>();//账号集合
        //        foreach (var obj in Ulist)
        //        {
        //            liscodename.Add(obj.NAME);
        //        }
        //        // DataTable dt = GetADUsers();//AD表

        //        foreach (DataRow r in dtad.Rows)
        //        {
        //            if (!liscodename.Contains(Convert.ToString(r["sAMAccountName"])))//userPrincipalName
        //            {
        //                WOO_USER u = new WOO_USER();
        //                u.ADDRESS = Convert.ToString(r["streetAddress"]);//地址
        //                u.PASSWORD = "95B13B93E52C7C1FD2D2A1F341844C71";//密码
        //                u.MODIFY_DATETIME = System.DateTime.Now;
        //                u.MODIFY_USER_ID = 1;
        //                //u.NAME = Convert.ToString(r["userPrincipalName"]);//AD账号
        //                u.NAME = Convert.ToString(r["sAMAccountName"]);//AD账号
        //                u.REMARK = Convert.ToString(r["description"]);//AD描述
        //                u.SEX = 6;//男,默认
        //                u.AGE = 0;//默认
        //                u.LASTNAME = Convert.ToString(r["sn"]);////                u.FIRSTNAME = Convert.ToString(r["givenName"]);////                u.DISPLAY_NAME = Convert.ToString(r["displayName"]);//显示名称
        //                u.TEL = Convert.ToString(r["telephoneNumber"]);//电话
        //                u.MOBILE = Convert.ToString(r["mobile"]);//其他号码-手机
        //                u.EMAIL = Convert.ToString(r["mail"]);//Email
        //                u.ENTRY_DATETIME = System.DateTime.Now;//入职时间
        //                u.ID_NO = "";//身份证号码
        //                u.DEPARTMENT_ID = 1;
        //                u.ROLE_ID = 15;//初始化角色
        //                u.STATE = 1;//未启用,默认
        //                u.CREATE_USER_ID = 1;//建立ID
        //                u.CREATE_DATETIME = System.DateTime.Now;
        //                u.IS_DELETE = 0;
        //                u.START = 0;
        //                Woo.BLL.WooSetting.User.Add(u);


        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        LogUtility.WriteErrorLog(ex);
        //    }



        //}
        #endregion
        #region 最终同步的方法///同步账号
        /// <summary>
        /// 同步账号
        /// </summary>
        public void SysAdAccount()
        {
            try
            {
                SynAll();//选装载datatable
                //SynUser(dt);
            }
            catch (Exception ex)
            {

               // Woo.Utility.LogUtility.WriteErrorLog(ex);
            }
        }
        #endregion


        #region 登陆-----登陆
        /// <summary>
        /// 验证AD用户是否登录成功
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>返回登陆状态</returns>
        public static string ADlogin(string userName, string password)
        {
            string isLogin = "100";
            try
            {
                DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domainName), userName, password,AuthenticationTypes.ServerBind);
                entry.RefreshCache();
                isLogin = "200";

            }
            catch (Exception ex)
            {
                var c = ((System.DirectoryServices.DirectoryServicesCOMException)(ex)).ExtendedErrorMessage;
                if (c.Contains("data 533"))
                {
                    isLogin = "501";//标示AD账号被禁用了
                }
                else if (c.Contains("data 52e"))
                {

                    isLogin = "502";//未知用户或者密码错误
                }
                else
                {

                    isLogin = "500";//怕出现漏网判断,500的时候直接给出用户名密码以及账号被禁用
                }
            }
            return isLogin;
        }

        /// <summary>
        /// 登陆方式2
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string  ADLogin2(string userName, string password)
        {
            //// sample : 
            //// LDAP://xxx.com 
           /// string domain = System.Configuration.ConfigurationManager.AppSettings["AD_Domain"];
            string msg="";
            try
            {
                
                DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domainName), userName, password);
                object obj = entry.NativeObject;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "((objectClass=user))";
                //search.Filter = string.Format("(objectClass=user)(SAMAccountName={0})", userName);
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();
                if (result == null){
                   msg="登陆失败";
                }
                msg="登陆成功!";
            }
            catch (Exception ex)
            {
               
              msg=ex.Message;
            }


            return msg;
        }
        /// <summary>
        /// AD校验-也可以使用
        /// </summary>
        /// <param name="userName">[email protected]账号必须这样</param>
        /// <param name="password">Lh!12345</param>
        public static void AdLogin3(string userName, string password)
        {

            string path = string.Format("LDAP://{0}", domainName); //"LDAP://192.168.1.1/";
            DirectoryEntry de = new DirectoryEntry(path, userName, password, AuthenticationTypes.Secure);
            DirectorySearcher ds = new DirectorySearcher(de);
            //ds.Filter = "(&(objectClass=user)(cn=张三))";
            ds.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", "zhansan");
            SearchResult result = ds.FindOne();
            if (result != null)
            {
                DirectoryEntry userEntry = result.GetDirectoryEntry();
               
            }



        }

        /// <summary>
        ///认证成功返回True.本地测试认证通过
        /// </summary>
        /// <param name="strUsername_">User name</param>
        /// <param name="strPassword_">User password</param>
        /// <returns>认证成功返回True</returns>
        public static bool IsAuthenticated(string strUsername_, string strPassword_)
        {
            using (var pc = new PrincipalContext(ContextType.Domain, domainName))
                return pc.ValidateCredentials(strUsername_, strPassword_);
        }
        #endregion

    }
}


这就是AD相关操作,测试通过

 

以上是关于关于AD校验代码的主要内容,如果未能解决你的问题,请参考以下文章

关于vue打包是因代码校验报错

关于js----------------分享前端开发常用代码片段

关于在各浏览器中插入音频文件的html代码片段

Android Place自动填充片段:无法设置文字

springcloud报错-------关于 hystrix 的异常 FallbackDefinitionException:fallback method wasn't found(代码片段

Android App 安全的HTTPS 通信