C# LDAP 管理(创建新用户)

来源:互联网 发布:华杉孙子兵法知乎 编辑:程序博客网 时间:2024/06/05 20:35

转自:http://blog.csdn.net/dannywj1371/article/details/16862183

今天用C#实现了一套LDAP域账号的创建和查询,感受挺多。

算是第一次接触LDAP吧,之前曾经做了一个登录的验证,就是查询功能,那个相对比较简单,用到了一个方法就搞定了。

这次的需求是要用编程的方式创建域账号,实现域登陆。


首先回顾一下之前查询用到的代码:

[csharp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static bool TryAuthenticate(string userName, string password)  
  2. {  
  3.     string domain = "litb-inc.com";  
  4.     bool isLogin = false;  
  5.     try  
  6.     {  
  7.         DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), userName, password);  
  8.         entry.RefreshCache();  
  9.         DBLog.Debug("check success");  
  10.         isLogin = true;  
  11.     }  
  12.     catch (Exception ex)  
  13.     {  
  14.         DBLog.Debug("域验证抛出异常 :" + ex.Message + ex.InnerException);  
  15.         isLogin = false;  
  16.     }  
  17.     return isLogin;  
  18. }  

这是验证指定用户是否在域里认证通过。


接下来,实现创建域账户的操作。在网上找到了一个操作类:


[csharp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5. using System.DirectoryServices;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Text.RegularExpressions;  
  9.   
  10. namespace Litb.HRExtension  
  11. {  
  12.     public static class AdHerlp  
  13.     {  
  14.         #region 创建AD连接  
  15.         /// <summary>  
  16.         /// 创建AD连接  
  17.         /// </summary>  
  18.         /// <returns></returns>  
  19.         public static DirectoryEntry GetDirectoryEntry()  
  20.         {  
  21.             DirectoryEntry de = new DirectoryEntry();  
  22.             de.Path = "LDAP://testhr.com/CN=Users,DC=testhr,DC=com";  
  23.             de.Username = @"administrator";  
  24.             de.Password = "litb20!!";  
  25.             return de;  
  26.   
  27.             //DirectoryEntry entry = new DirectoryEntry("LDAP://testhr.com", "administrator", "litb20!!", AuthenticationTypes.Secure);  
  28.             //return entry;  
  29.   
  30.         }  
  31.         #endregion  
  32.  
  33.         #region 获取目录实体集合  
  34.         /// <summary>  
  35.         ///  
  36.         /// </summary>  
  37.         /// <param name="DomainReference"></param>  
  38.         /// <returns></returns>  
  39.         public static DirectoryEntry GetDirectoryEntry(string DomainReference)  
  40.         {  
  41.             DirectoryEntry entry = new DirectoryEntry("LDAP://testhr.com" + DomainReference, "administrator""litb20!!", AuthenticationTypes.Secure);  
  42.             return entry;  
  43.         }  
  44.         #endregion  
  45.     }  
  46.   
  47.     //AD操作类  
  48.   
  49.     //myDirectory.cs  
  50.   
  51.    public  class myDirectory  
  52.     {  
  53.   
  54.         /// <summary>  
  55.         /// 判断用户是否存在  
  56.         /// </summary>  
  57.         /// <param name="UserName"></param>  
  58.         /// <returns></returns>  
  59.         public bool UserExists(string UserName)  
  60.         {  
  61.             DirectoryEntry de = AdHerlp.GetDirectoryEntry();  
  62.             DirectorySearcher deSearch = new DirectorySearcher();  
  63.             deSearch.SearchRoot = de;  
  64.             deSearch.Filter = "(&(objectClass=user) (cn=" + UserName + "))";  
  65.             SearchResultCollection results = deSearch.FindAll();  
  66.             if (results.Count == 0)  
  67.             {  
  68.                 return false;  
  69.             }  
  70.             else  
  71.             {  
  72.                 return true;  
  73.             }  
  74.         }  
  75.         /// <summary>  
  76.         /// 修改用户属性  
  77.         /// </summary>  
  78.         /// <param name="de"></param>  
  79.         /// <param name="PropertyName"></param>  
  80.         /// <param name="PropertyValue"></param>  
  81.         public static void SetProperty(DirectoryEntry de, string PropertyName, string PropertyValue)  
  82.         {  
  83.             if (PropertyValue != null)  
  84.             {  
  85.                 if (de.Properties.Contains(PropertyName))  
  86.                 {  
  87.                     de.Properties[PropertyName][0] = PropertyValue;  
  88.                 }  
  89.                 else  
  90.                 {  
  91.                     de.Properties[PropertyName].Add(PropertyValue);  
  92.                 }  
  93.             }  
  94.         }  
  95.   
  96.         /// <summary>  
  97.         /// 生成随机密码  
  98.         /// </summary>  
  99.         /// <returns></returns>  
  100.         public string SetSecurePassword()  
  101.         {  
  102.             //RandomPassword rp = new RandomPassword();  
  103.             return "qwe123!@#";  
  104.         }  
  105.   
  106.         /// <summary>  
  107.         /// 设置用户新密码  
  108.         /// </summary>  
  109.         /// <param name="path"></param>  
  110.         public void SetPassword(DirectoryEntry newuser)  
  111.         {  
  112.             //DirectoryEntry usr = new DirectoryEntry();  
  113.             //usr.Path = path;  
  114.             //usr.AuthenticationType = AuthenticationTypes.Secure;  
  115.               
  116.             //object[] password = new object[] { SetSecurePassword() };  
  117.             //object ret = usr.Invoke("SetPassword", password);  
  118.             //usr.CommitChanges();  
  119.             //usr.Close();  
  120.   
  121.             newuser.AuthenticationType = AuthenticationTypes.Secure;  
  122.             object[] password = new object[] { SetSecurePassword() };  
  123.             object ret = newuser.Invoke("SetPassword", password);  
  124.             newuser.CommitChanges();  
  125.             newuser.Close();  
  126.   
  127.         }  
  128.   
  129.         /// <summary>  
  130.         /// 启用用户帐号  
  131.         /// </summary>  
  132.         /// <param name="de"></param>  
  133.         private static void EnableAccount(DirectoryEntry de)  
  134.         {  
  135.             //UF_DONT_EXPIRE_PASSWD 0x10000  
  136.             int exp = (int)de.Properties["userAccountControl"].Value;  
  137.             de.Properties["userAccountControl"].Value = exp | 0x0001;  
  138.             de.CommitChanges();  
  139.             //UF_ACCOUNTDISABLE 0x0002  
  140.             int val = (int)de.Properties["userAccountControl"].Value;  
  141.             de.Properties["userAccountControl"].Value = val & ~0x0002;  
  142.             de.CommitChanges();  
  143.         }  
  144.   
  145.         /// <summary>  
  146.         /// 添加用户到组  
  147.         /// </summary>  
  148.         /// <param name="de"></param>  
  149.         /// <param name="deUser"></param>  
  150.         /// <param name="GroupName"></param>  
  151.         public static void AddUserToGroup(DirectoryEntry de, DirectoryEntry deUser, string GroupName)  
  152.         {  
  153.             DirectorySearcher deSearch = new DirectorySearcher();  
  154.             deSearch.SearchRoot = de;  
  155.             deSearch.Filter = "(&(objectClass=group) (cn=" + GroupName + "))";  
  156.             SearchResultCollection results = deSearch.FindAll();  
  157.   
  158.             bool isGroupMember = false;  
  159.   
  160.             if (results.Count > 0)  
  161.             {  
  162.                 DirectoryEntry group = AdHerlp.GetDirectoryEntry(results[0].Path);  
  163.   
  164.                 object members = group.Invoke("Members"null);  
  165.                 foreach (object member in (IEnumerable)members)  
  166.                 {  
  167.                     DirectoryEntry x = new DirectoryEntry(member);  
  168.                     if (x.Name != deUser.Name)  
  169.                     {  
  170.                         isGroupMember = false;  
  171.                     }  
  172.                     else  
  173.                     {  
  174.                         isGroupMember = true;  
  175.                         break;  
  176.                     }  
  177.                 }  
  178.   
  179.                 if (!isGroupMember)  
  180.                 {  
  181.                     group.Invoke("Add"new object[] { deUser.Path.ToString() });  
  182.                 }  
  183.                 group.Close();  
  184.             }  
  185.             return;  
  186.         }  
  187.   
  188.         /// <summary>  
  189.         /// 创建一个新用户  
  190.         /// </summary>  
  191.         /// <param name="employeeID"></param>  
  192.         /// <param name="name"></param>  
  193.         /// <param name="login"></param>  
  194.         /// <param name="email"></param>  
  195.         /// <param name="group"></param>  
  196.         public void CreateNewUser(string employeeID, string name, string login, string email, string group)  
  197.         {  
  198.             //Catalog catalog = new Catalog();  
  199.             DirectoryEntry de = AdHerlp.GetDirectoryEntry();  
  200.   
  201.             /// 1. Create user account  
  202.             DirectoryEntries users = de.Children;  
  203.             DirectoryEntry newuser = users.Add("CN=" + login, "user");  
  204.   
  205.             /// 2. Set properties  
  206.             SetProperty(newuser, "employeeID", employeeID);  
  207.             SetProperty(newuser, "givenname", name);  
  208.             SetProperty(newuser, "SAMAccountName", login);  
  209.             SetProperty(newuser, "userPrincipalName", login);  
  210.             SetProperty(newuser, "mail", email);  
  211.             SetProperty(newuser, "Description""Create User By HrESS System");  
  212.   
  213.             newuser.CommitChanges();  
  214.   
  215.             /// 3. Set password  
  216.             newuser.AuthenticationType = AuthenticationTypes.Secure;  
  217.             object[] password = new object[] { SetSecurePassword() };  
  218.             object ret = newuser.Invoke("SetPassword", password);  
  219.             newuser.CommitChanges();  
  220.             //newuser.Close();  
  221.   
  222.   
  223.             //SetPassword(newuser);  
  224.             //newuser.CommitChanges();  
  225.   
  226.             /// 4. Enable account             
  227.             EnableAccount(newuser);  
  228.   
  229.             /// 5. Add user account to groups  
  230.             AddUserToGroup(de, newuser, group);  
  231.   
  232.             /// 6. Create a mailbox in Microsoft Exchange     
  233.             //GenerateMailBox(login);  
  234.   
  235.             newuser.Close();  
  236.             de.Close();  
  237.         }  
  238.         /// <summary>  
  239.         /// 禁用一个帐号  
  240.         /// </summary>  
  241.         /// <param name="EmployeeID"></param>  
  242.         public void DisableAccount(string EmployeeID)  
  243.         {  
  244.             DirectoryEntry de = AdHerlp.GetDirectoryEntry();  
  245.             DirectorySearcher ds = new DirectorySearcher(de);  
  246.             ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" + EmployeeID + "))";  
  247.             ds.SearchScope = SearchScope.Subtree;  
  248.             SearchResult results = ds.FindOne();  
  249.   
  250.             if (results != null)  
  251.             {  
  252.                 DirectoryEntry dey = AdHerlp.GetDirectoryEntry(results.Path);  
  253.                 int val = (int)dey.Properties["userAccountControl"].Value;  
  254.                 dey.Properties["userAccountControl"].Value = val | 0x0002;  
  255.                 dey.Properties["msExchHideFromAddressLists"].Value = "TRUE";  
  256.                 dey.CommitChanges();  
  257.                 dey.Close();  
  258.             }  
  259.   
  260.             de.Close();  
  261.         }  
  262.         /// <summary>  
  263.         /// 修改用户信息  
  264.         /// </summary>  
  265.         /// <param name="employeeID"></param>  
  266.         /// <param name="department"></param>  
  267.         /// <param name="title"></param>  
  268.         /// <param name="company"></param>  
  269.         public void ModifyUser(string employeeID, string department, string title, string company)  
  270.         {  
  271.             DirectoryEntry de = AdHerlp.GetDirectoryEntry();  
  272.             DirectorySearcher ds = new DirectorySearcher(de);  
  273.             ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" + employeeID + "))";  
  274.             ds.SearchScope = SearchScope.Subtree;  
  275.             SearchResult results = ds.FindOne();  
  276.   
  277.             if (results != null)  
  278.             {  
  279.                 DirectoryEntry dey = AdHerlp.GetDirectoryEntry(results.Path);  
  280.                 SetProperty(dey, "department", department);  
  281.                 SetProperty(dey, "title", title);  
  282.                 SetProperty(dey, "company", company);  
  283.                 dey.CommitChanges();  
  284.                 dey.Close();  
  285.             }  
  286.   
  287.             de.Close();  
  288.         }  
  289.   
  290.         /// <summary>  
  291.         /// 检验Email格式是否正确  
  292.         /// </summary>  
  293.         /// <param name="mail"></param>  
  294.         /// <returns></returns>  
  295.         public bool IsEmail(string mail)  
  296.         {  
  297.             Regex mailPattern = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");  
  298.             return mailPattern.IsMatch(mail);  
  299.         }  
  300.         /// <summary>  
  301.         /// 搜索被修改过的用户  
  302.         /// </summary>  
  303.         /// <param name="fromdate"></param>  
  304.         /// <returns></returns>  
  305.         public DataTable GetModifiedUsers(DateTime fromdate)  
  306.         {  
  307.             DataTable dt = new DataTable();  
  308.             dt.Columns.Add("EmployeeID");  
  309.             dt.Columns.Add("Name");  
  310.             dt.Columns.Add("Email");  
  311.   
  312.             DirectoryEntry de = AdHerlp.GetDirectoryEntry();  
  313.             DirectorySearcher ds = new DirectorySearcher(de);  
  314.   
  315.             StringBuilder filter = new StringBuilder();  
  316.             filter.Append("(&(objectCategory=Person)(objectClass=user)(whenChanged>=");  
  317.             filter.Append(ToADDateString(fromdate));  
  318.             filter.Append("))");  
  319.   
  320.             ds.Filter = filter.ToString();  
  321.             ds.SearchScope = SearchScope.Subtree;  
  322.             SearchResultCollection results = ds.FindAll();  
  323.   
  324.             foreach (SearchResult result in results)  
  325.             {  
  326.                 DataRow dr = dt.NewRow();  
  327.                 DirectoryEntry dey = AdHerlp.GetDirectoryEntry(result.Path);  
  328.                 dr["EmployeeID"] = dey.Properties["employeeID"].Value;  
  329.                 dr["Name"] = dey.Properties["givenname"].Value;  
  330.                 dr["Email"] = dey.Properties["mail"].Value;  
  331.                 dt.Rows.Add(dr);  
  332.                 dey.Close();  
  333.             }  
  334.   
  335.             de.Close();  
  336.             return dt;  
  337.         }  
  338.   
  339.         /// <summary>  
  340.         /// 格式化AD的时间  
  341.         /// </summary>  
  342.         /// <param name="date"></param>  
  343.         /// <returns></returns>  
  344.         public string ToADDateString(DateTime date)  
  345.         {  
  346.             string year = date.Year.ToString();  
  347.             int month = date.Month;  
  348.             int day = date.Day;  
  349.   
  350.             StringBuilder sb = new StringBuilder();  
  351.             sb.Append(year);  
  352.             if (month < 10)  
  353.             {  
  354.                 sb.Append("0");  
  355.             }  
  356.             sb.Append(month.ToString());  
  357.             if (day < 10)  
  358.             {  
  359.                 sb.Append("0");  
  360.             }  
  361.             sb.Append(day.ToString());  
  362.             sb.Append("000000.0Z");  
  363.             return sb.ToString();  
  364.         }  
  365.     }  
  366. }  

有了这个操作类,就可以进行域账号的创建了,调用示例:

[csharp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Console.WriteLine("Begin CreateNewUser");  
  2. string name = "wj" + System.Guid.NewGuid().ToString().Substring(0, 5);  
  3. string id = System.Guid.NewGuid().ToString().Substring(0, 5);my.CreateNewUser(id, name, name, name + "@testhr.com""testhr.com/Users");  
  4. Console.WriteLine("域用户名创建成功:" + name);  

注意域账号的用户名不能有类似-,下划线之类的特殊字符。


在最初尝试的时候,创建对象 DirectoryEntry的时候总是有问题,最终这两种方式都是有效的:

            DirectoryEntry de = new DirectoryEntry();
            de.Path = "LDAP://testhr.com/CN=Users,DC=testhr,DC=com";
            de.Username = @"administrator";
            de.Password = "litb20!!";
            return de;

            DirectoryEntry entry = new DirectoryEntry("LDAP://testhr.com", "administrator", "litb20!!", AuthenticationTypes.Secure);
            return entry;


其次,在创建完用户以后,需要设置用户的密码,这个方法总是报错,后来经过检查,发现如果只传递path字符串,是不行的,必须操作现有对象的Invoke方法才可以!

或者传递对象引用。


最终,成功创建了域账户。


在测试的时候,同一台机器加入了多个账号后,就会有问题,报出类似这样的错误:


最终,可以通过在服务器上删除这台电脑的方式来解决,或者重命名本地计算机名称。





0 0
原创粉丝点击